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

297
Visualizações
Why is the value on display not in sync with value logged to console?

Can anyone tell me why at button click, the value outputted to the console is always one unit smaller than displayed on the screen? The values are not in sync as expected.

Example below in React

In Child:

import React, {useState } from "react";

export const ChildComp = ({getNumProps}) => {
    const [num, setNum] = useState(0);
    

    const onPlusClick = () => {
        
        if (num< 12) {
          setNum(num + 1);// num does not increase immediately after this line, except when focus reenters here on second method call
        }
        
        getNumProps(num);
      }

    return(
        <div>
            <button onClick={onPlusClick}>
                Click to increment
            </button>
            {num}
        </div>
    );
}

In parent

import { ChildComp } from "./ChildComp"

export const ParentComp = () => {

    const getNum= (num) => {
        console.log(num);
    }

    return (<ChildComp getNumProps={getNum}/>)
}

The page initially shows 0

  • When I click once the number increments to 1, but console displays 0
  • When I click once the number increments to 2, but console displays 1 I should see in the console the same as the page display

Appreciate if you can leave a commen on how the question can be improved.

This is a child to parent communication example. Also, any objections about standards used, please let me know.

Thanks.

Update: I notice the values would be in sync if instead of getNumProps(num); I did getNumProps(num + 1); but that doesn't change the fact that previously on this line setNum(num + 1);, as already pointed out in the comment, num does not increase immediately after this line, except when focus reenters here on second method call. Not sure why.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The prop function getNumProps is a side effect, and should be put into a hook, instead of inside of that onPlusClick function.

Instead, do this:

useEffect(() => {
   getNumProp(num);
}, [num]);

Alternatively, to avoid the error: "React Hook useEffect has a missing dependency: 'getNumProps'. See this doc on using the useCallback hook

const callback = useCallback(() => {
   getNumProp(num);
}, [num]);

function onPlusClick(...) {
   ...
   callback();
}

The change to the state of num will cause a re-render of the child component, not the parent.

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