Today's task is to create a usePrevious() hook that returns the previous value, with an initial previous value of undefined.
The boilerplate code looks like this:
export function usePrevious<T>(value: T): T | undefined {
// your code here
}
// if you want to try your code on the right panel
// remember to export App() component like below
// export function App() {
// return <div>your app</div>
// }
We will use a ref to hold the value of the state, to prevent re-renders.
const ref = useRef<T>()
To store the previous value after every render, the .current property of the ref is used
useEffect(() => {
ref.current = value
}, [value])
return ref.current
The useEffect hook runs after every render, to hold the previous value and prevent it from updating. To see an example, we have a count state to show the present value and a prevCount state to show the previous value we stored. Here's what the complete code looks like:
import React, { useEffect, useRef, useState } from 'react';
export function usePrevious<T>(value: T): T | undefined {
// your code here
const ref=useRef<T>()
useEffect(() => {
ref.current = value;
}, [value])
return ref.current;
}
// if you want to try your code on the right panel
// remember to export App() component like below
export function App() {
const [count, setCount] = useState(0)
const prevCount = usePrevious(count)
return(
<div>
<p>Now: {count}, previous{prevCount}</p>
<button onClick={() => setCount(c => c + 1)}>Increment</button>
</div>)
}
That's all folks!
Top comments (0)