React usePrevious Hook

ReactReactBeginner
Practice Now

This tutorial is from open-source community. Access the source code

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.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL react(("`React`")) -.-> react/FundamentalsGroup(["`Fundamentals`"]) react(("`React`")) -.-> react/AdvancedConceptsGroup(["`Advanced Concepts`"]) react(("`React`")) -.-> react/StateManagementGroup(["`State Management`"]) react/FundamentalsGroup -.-> react/jsx("`JSX`") react/FundamentalsGroup -.-> react/event_handling("`Handling Events`") react/AdvancedConceptsGroup -.-> react/hooks("`React Hooks`") react/StateManagementGroup -.-> react/use_state_reducer("`Using useState and useReducer`") subgraph Lab Skills react/jsx -.-> lab-38404{{"`React usePrevious Hook`"}} react/event_handling -.-> lab-38404{{"`React usePrevious Hook`"}} react/hooks -.-> lab-38404{{"`React usePrevious Hook`"}} react/use_state_reducer -.-> lab-38404{{"`React usePrevious Hook`"}} end

React usePrevious Hook

index.html and script.js have already been provided in the VM. In general, you only need to add code to script.js and style.css.

To store the previous state or props, you can create a custom hook. Here are the steps:

  1. Define a custom hook that takes a value argument.
  2. Use the useRef() hook to create a ref for the value.
  3. Use the useEffect() hook to remember the latest value.
  4. Return the ref.current value.
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.

Other React Tutorials you may like