astoilkov / use-local-storage-state

React hook that persists data in localStorage
MIT License
1.09k stars 39 forks source link

move removeItem to useCallback #69

Closed iamkd closed 1 month ago

iamkd commented 1 month 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 1 month ago

Ah, yes.

Thank you for your work!