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

265
Vistas
Child component is rerendering despite using useMemo,

I have code like this:

export default function App() {
  const [items, setItems] = useState([]);

  const handleClick = (number) => {
    console.log("typeof", typeof number);
    items.includes(number)
      ? setItems((prevState) =>
          prevState.filter((prevSlot) => prevSlot != number)
        )
      : setItems((items) => [...items, number]);
  };

  useEffect(() => {
    console.log("items", items);
  }, [items]);

  return (
    <div className="App">
      <ButtonDiv handleClick={handleClick} slot="5" />
      <ButtonDiv handleClick={handleClick} slot="10" />
      <ButtonDiv handleClick={handleClick} slot="15" />
      <ButtonDiv handleClick={handleClick} slot="20" />
      <ButtonDiv handleClick={handleClick} slot="25" />
    </div>
  );
}

ButtonDiv

const ButtonDiv = ({ handleClick, slot }) => {
  return useMemo(() => {
    console.log("renderButton");
    return <button onClick={() => handleClick(slot)}>Click me</button>;
  }, [handleClick, slot]);
};

Here, on clicking on button div, it is re-rendering for every button components, how could I prevent it from happening, and still keep maintaining the core functionality of toggling value when clicked on button.

codesandbox

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

0

Every time App renders, it generates a new handleClick function and passes it as a prop to <ButtonDiv>.

The useMemo hook lists handleClick in the dependencies.

Since handleClick has changed, the memoized function has to be called to regenerate the result.


You probably want to wrap the creation of handleClick in useCallback.

about 4 years ago · Juan Pablo Isaza Denunciar

0

You are sending a new reference of handleClick every time that you are rendering the App

With some modifications and using useCallback you can make it work without re-rendering the divButtons, useCallback without deps will generate always the same instance so it won't be refreshing your buttons.

Had to remove the items state, since if you add it you will have always the instance of the state at the moment the handleClick is created, so using just the set state and the prevState we can manage to make it work

  const handleClick = useCallback(
    (number) => {
      console.log("typeof", typeof number, number);
        setItems((prevState) =>
            prevState.includes(number) ? 
              prevState.filter((prevSlot) => prevSlot != number) :
              [...prevState, number]
          )
    },
    []
  );

Adding image of working example.

enter image description here

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