Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

123
Vistas
Unknown behavior when using react useState and useEffect

I have this code :

function Parent(props) {

    const [items, setItems] = useState([]);
    const [itemArr, setItemArr] = useState([]);
    const [reRender, setReRender] = useState(false);

    useEffect(() => {
        let _items = items.slice(0).reverse().map((item, idx) => {
            return {
                type: {
                    subject: item.type,
                    type: "text"
                },
                child: {
                    subject: <Child
                                data = {item}
                             ></Child>,
                    type: "inline"
                },
            }
        });

        setItemArr(_items);
    }, [reRender])

    function newItem(info) {

        let [date, time] = getDate();

        let tmp = items;
        tmp.push({
            id: items.length,
            type: info.type,
            date: date,
            time: time
        });
        
        setItems(tmp);
        setReRender(!reRender);
    }

    return (
            <MyTable
                 items = {itemArr}
            ></MyTable>
    )
}

and my Child component:


export default function ScanTimer(props) {

    console.log(props.data);

    useEffect(() => {
        console.log(props.data);
    }, []);

    return(
        <div></div>
    )
}

when I run my app, and add two item to the table, first console.log in child component (the one that is out of useEffect) shows right data. but last one (in useEffect) shows wrong data (the data that is for first item inserted into table).

it happens also when I init a state In this way:

const [data, setData] = useState(props.data);

in the Child element.

I don't know why it happens. can somebody help me??

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

first console.log in child component (the one that is out of useEffect) shows right data

That runs every time the component is rendered. It will always show the latest data.

but last one (in useEffect) shows wrong data (the data that is for first item inserted into table

The runs every time the dependency list changes.

So it runs on the first render (with the first value) because the dependencies have changed from "didn't exist" to "exists".

Then on subsequent renders, since there are no dependancies in the list (you passed an empty array), they haven't changed, so it doesn't run.

That is the point of useEffect.

If you want it to run when the data changes, you have to include that in the dependency list.

useEffect(() => {
    console.log(props.data);
}, [props.data]);
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda