Develumpen

See if a React property has changed

Sometimes you want to avoid unnecessary renders without knowing what you're doing. useCallback here, useMemo there, but nothing seems to work.

With the help of useRef you can easily track what properties are changing thus triggering a useEffect hook. Replace callback with the name of the property you want to track.

const prevCallbackRef = useRef(callback);

useEffect(() => {
  if (prevCallbackRef.current !== callback) {
    console.log('callback has changed');
  }

  // Update refs with current values
  prevCallbackRef.current = callback;
}, [callback]);
#react