This solution is generated by ChatGPT, correctness is not guaranteed. You might also be able to find a solution fromcommunity postsor official solution page.
AI solution for React Coding Question on BFE.dev
5. usePrevious()
Here's how you can create the usePrevious()
hook in React:
import { useRef, useEffect } from 'react';
function usePrevious(value) {
const ref = useRef();
useEffect(() => {
ref.current = value;
}, [value]);
return ref.current;
}
This hook uses the useRef()
hook to create a reference that persists across re-renders of the component. It also uses the useEffect()
hook to update the reference whenever the value
changes. Finally, it returns the current value of the reference, which represents the previous value of value
on the previous render.
You can then use this hook in your components like this:
function MyComponent() {
const [count, setCount] = useState(0);
const previousCount = usePrevious(count);
return (
<div>
<p>Count: {count}</p>
<p>Previous count: {previousCount}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
In this example, the usePrevious()
hook returns the previous value of count
whenever it changes. The current value of count
is also displayed on the screen, along with the previous value. Whenever the button is clicked, the count is incremented, and the previous count is updated to the previous value of count
.