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