Skip to content

Latest commit

 

History

History
19 lines (15 loc) · 674 Bytes

extra-usePrevious-hook.md

File metadata and controls

19 lines (15 loc) · 674 Bytes

Extra: usePrevious: Custom hook example using useRef

Since useRef can store the value across a re-render you can use it to store a value from a previous render, i.e. as a custom hook:

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

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

Example taken from the section "How to get the previous props or state?" in the React docs