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

127
Visualizações
Memorize react change handler

I know that react component will render everytime state changes and useCallBack memorize function depending on the dependency array provided.

But If I have this:

<input type="text" name="name" value={values.name} onChange={handleChange} />
<input type="text" name="phone" value={values.phone} onChange={handleChange} />

Whats the difference between these two handleChange implementation?

const handleChange = e => {
  setValues(values => ({ ...values, [e.target.name]: e.target.value }))
}

and

const handleChange = useCallback(e => {
  setValues(values => ({ ...values, [e.target.name]: e.target.value }))
}), [])

Code snippet needed in comment

const Child = () => {
  console.log("Child rerendered");
  return <div>Hello World </div>;
};
export default function App() {
  const [count, setCount] = useState(0);
  console.log("Parent rerendered");
  return (
    <div className="App">
      <Child />
      <button
        onClick={() => {
          setCount((x) => x + 1);
        }}
      >
        {count}
      </button>
    </div>
  );
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The difference is that with the second one using useCallback, you'll keep using the first handleChange function you create; with the first one where you don't use useCallback, you're creating a new handler function each time. (Technically, you create a new one every time in both cases, but useCallback will only return the first one that gets created, because you've provided an empty dependency array.) More in the documentation.

It doesn't matter much when giving the handler function to input or other native HTML elements, or even simple components. If you were providing this handler function to a complex component, it might be better to use useCallback if that complex component optimizes re-rendering (for instance, with React.memo, PureComponent, or shouldComponentUpdate).

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