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

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

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 Relatório

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