Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

124
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda