Example of usePrevious() Custom hook in react.js

Example of usePrevious() Custom hook in react.js

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 (
      <h1>Previous Value Example</h1>
      <p>Previous count: {previousCount}</p>
      <p>Current count: {count}</p>
      <button onClick={increment}>Increment</button>

export default MyComponent;

In this example:

  • We create a functional component called MyComponent.

  • We use useState to make a state variable count and usePrevious to keep track of count's previous value.

  • We use useEffect to print the old and new values of count when it changes.

  • Clicking the button runs the increment function, which adds 1 to count.

  • 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.

Did you find this article valuable?

Support LingarajTechhub All About Programming by becoming a sponsor. Any amount is appreciated!