a year ago3min read

usePrevious hook using React.js.

usePrevious Image

State management is at the core of every React application. React provides various tools and techniques to manage and manipulate state. One common scenario is the need to track the previous value of a state variable or a prop. In this blog post, we will explore how to create and use a custom hook called usePrevious to achieve this in React.

The Problem

Consider a situation where you have a component with a state variable, and you want to perform some action when that variable changes. However, you also need to know what the previous value of that variable was. React doesn't provide a built-in way to access the previous state directly, which is where the usePrevious custom hook comes in handy.

Creating the usePrevious Hook

To create the usePrevious hook, we'll use React's useRef hook to store and access the previous value of a state variable or prop. Here's how you can define the usePrevious hook:

import { useRef, useEffect } from "react";

function usePrevious(value) {
  const ref = useRef();

  useEffect(() => {
    ref.current = value;
  }, [value]);

  return ref.current;
}

The usePrevious hook takes a single argument, value, which is the state variable or prop you want to track. It uses the useRef hook to create a mutable ref object and the useEffect hook to update the ref's value whenever value changes. Finally, it returns the previous value stored in the ref.

Using the usePrevious Hook

Now that we have our usePrevious hook, let's see how we can use it in a React component. Consider a simple example where we have a counter component:

import React, { useState } from "react";

function Counter() {
  const [count, setCount] = useState(0);
  const prevCount = usePrevious(count);

  const increment = () => {
    setCount(count + 1);
  };

  return (
    <div>
      <p>Current Count: {count}</p>
      <p>Previous Count: {prevCount}</p>
      <button onClick={increment}>Increment</button>
    </div>
  );
}

export default Counter;

In this example, we're using the usePrevious hook to track the previous value of the count state variable. We can then display it in our component. Every time the "Increment" button is clicked, the count state updates, and the previous value is displayed alongside the current value.

Benefits of Using usePrevious

Using the usePrevious hook can be incredibly beneficial in various scenarios, including:

  1. Animating Transitions: You can compare the previous and current values of a prop or state to create smooth animations or transitions when they change.

  2. Optimizing Side Effects: You can conditionally trigger side effects or API calls based on changes in a value, avoiding unnecessary requests.

  3. Undo/Redo Functionality: It can be used to implement undo and redo functionality by keeping track of the previous states of your application.

  4. Debugging: During development, it's useful for debugging to have access to the previous state or prop values for better insight into component behavior.

Conclusion

The usePrevious custom hook is a powerful tool for tracking the previous value of a state variable or prop in React. By using this hook, you can enhance the functionality and behavior of your components, making them more flexible and responsive to changes. Whether you're building animations, optimizing side effects, or implementing undo/redo functionality, the usePrevious hook is a valuable addition to your React toolkit.

Remember that while this hook is versatile, it should be used judiciously, as excessive reliance on it can make your code more complex. Nevertheless, it's a valuable tool to have in your React development toolbox for those situations where you need to access the previous state or prop value.


Next Blogs

Implement Queue Using JS.

Learn how to implement a queue data structure in JavaScript, a fundamental concept for building various data structures and algorithms.

Implement stack using JS.

Learn how to implement a stack data structure in JavaScript, a fundamental concept for managing data in a Last-In, First-Out (LIFO) manner.