Home > database >  Child component is rerendering despite using useMemo,
Child component is rerendering despite using useMemo,

Time:06-24

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.

enter image description here

  • Related