Introduction
In this lab, we will explore the use of the usePrevious hook in React. This custom hook allows us to store the previous state or props of a component, which can be useful in a variety of scenarios. By creating a simple counter component and using the usePrevious hook, we will demonstrate how to implement this functionality in your React projects.
React usePrevious Hook
index.htmlandscript.jshave already been provided in the VM. In general, you only need to add code toscript.jsandstyle.css.
To store the previous state or props, you can create a custom hook. Here are the steps:
- Define a custom hook that takes a
valueargument. - Use the
useRef()hook to create areffor thevalue. - Use the
useEffect()hook to remember the latestvalue. - Return the
ref.currentvalue.
const usePrevious = (value) => {
const ref = React.useRef();
React.useEffect(() => {
ref.current = value;
});
return ref.current;
};
Here's an example of using the usePrevious hook:
const Counter = () => {
const [value, setValue] = React.useState(0);
const lastValue = usePrevious(value);
return (
<div>
<p>
Current: {value} - Previous: {lastValue}
</p>
<button onClick={() => setValue(value + 1)}>Increment</button>
</div>
);
};
ReactDOM.createRoot(document.getElementById("root")).render(<Counter />);
The Counter component displays the current and previous values of value. When the Increment button is clicked, value is updated and the previous value is stored using the usePrevious hook.
Please click on 'Go Live' in the bottom right corner to run the web service on port 8080. Then, you can refresh the Web 8080 Tab to preview the web page.
Summary
Congratulations! You have completed the React usePrevious Hook lab. You can practice more labs in LabEx to improve your skills.