Here's how to make a usePrevious()
hook in React, letting you see the last value of a state or prop:
import { useRef, useEffect } from 'react';
const usePrevious = (value) => {
const ref = useRef();
useEffect(() => {
ref.current = value;
}, [value]);
return ref.current;
};
export default usePrevious;
You can use this usePrevious
hook in your components to access the previous value of a state or prop. Here's how you can use it:
import React, { useState, useEffect } from 'react';
import usePrevious from './usePrevious'; // Assuming you've placed the hook in a separate file
const MyComponent = () => {
const [count, setCount] = useState(0);
const previousCount = usePrevious(count);
useEffect(() => {
console.log(`Previous count: ${previousCount}, Current count: ${count}`);
}, [count, previousCount]);
const increment = () => {
setCount((prevCount) => prevCount + 1);
};
return (
<div>
<h1>Previous Value Example</h1>
<p>Previous count: {previousCount}</p>
<p>Current count: {count}</p>
<button onClick={increment}>Increment</button>
</div>
);
};
export default MyComponent;
In this example:
We create a functional component called
MyComponent
.We use
useState
to make a state variablecount
andusePrevious
to keep track ofcount
's previous value.We use
useEffect
to print the old and new values ofcount
when it changes.Clicking the button runs the
increment
function, which adds 1 tocount
.We show the previous and current
count
values in the component.
The usePrevious
hook makes it easy to get the previous value of a state or prop in React components. It removes the need for repetitive logic, helps in reusing code, and makes components simpler and clearer.