astoilkov / use-local-storage-state

React hook that persists data in localStorage
MIT License
1.17k stars 41 forks source link

move removeItem to useCallback #69

Closed iamkd closed 3 months ago

iamkd commented 3 months ago

This PR wraps removeItem with useCallback to preserve its reference in most use cases.

Currently, removeItem does not have a stable reference. It is being re-initialized every time a value is changed. This is suboptimal, because calling removeItem should not re-initialize itself.

An example use case would be using it in a useEffect:

useEffect(() => {
  if (!user) {
    removeItem(); // causes infinite useEffect loop
  }
}, [user, removeItem]); 

While obviously there are ways to mitigate that, do extra checks etc., maintaining references as stable as possible should reduce possible bugs.

astoilkov commented 3 months ago

Ah, yes.

Thank you for your work!