kripod/react-hooks

Add `usePrevious` hook

kripod opened this issue · 1 comments

Motivation

Sometimes, the previous value of a variable may be needed through subsequent re-renders.

Basic example

function Counter() {
  const [count, setCount] = useState(0);
  const prevCount = usePrevious(count);
  return <h1>Now: {count}, before: {prevCount}</h1>;
}

Details

How to get the previous props or state? – React Hooks FAQ:

function usePrevious(value) {
  const ref = useRef();
  useEffect(() => {
    ref.current = value;
  });
  return ref.current;
}

This has been implemented by c6e2d5e, but tests are yet to be added.