Skip to content

Instantly share code, notes, and snippets.

@WrathChaos
Created April 21, 2020 13:52
Show Gist options
  • Save WrathChaos/d2366da0f475d7d2e14624300cabcf86 to your computer and use it in GitHub Desktop.
Save WrathChaos/d2366da0f475d7d2e14624300cabcf86 to your computer and use it in GitHub Desktop.
Use Effect with Previous State
function usePrevious(value) {
  const ref = useRef();

  useEffect(() => {
  ref.current = value;
  });

  return ref.current;
}

// USAGE
const [value, setValue] = useState(0);
const prevValue = usePrevious(value);
console.log(`${value}, prev: ${prevValue}`);

```javascript
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment