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

126
Vistas
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 Respuestas
Responde la pregunta

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 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