Get "PHP 8 in a Nuthshell" (Now comes with PHP 8.3)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Keeping track of the last value of state in React.js

When working with states in React.js, there comes a time when you might need to differentiate between the current and previous “state” of a state.

For instance, you’ve written an event that should only get triggered if the difference between the current and previous state matches a certain value.

Check this simple example.

import { useState } from "react";

export default function App() {
  const [name, setName] = useState("Amit");

  return (
    <>
      <h1>Current name: {name}</h1>
      <button onClick={() => setName("Cherika")}>Click Me!</button>
    </>
  );
}

Here in this component, the initial state for name is “Amit”. Now, when the “Click Me!” button is clicked, the state of name will be “Cherika”.

As you can tell, currently, we don’t have any means to check the previous state of name since we are keeping track of it.

To fix this, we can use the useRef hook to create an instance variable. This can be used further to store the previous state every time the state of name is updated using the useEffect hook like so.

import { useState, useRef, useEffect } from "react";

export default function App() {
  const [name, setName] = useState("Amit");
  const prevName = usePrevious(name);

  return (
    <>
      <h1>Current name: {name}</h1>
      <h1>Previous name: {prevName}</h1>
      <button onClick={() => setName("Cherika")}>Click Me!</button>
    </>
  );
}

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

  useEffect(() => {
    ref.current = value;
  });
  
  return ref.current;
}

As you can tell, we can create a custom hook called usePrevious which holds the logic to keep the previous state since the “ref” object here is a generic container whose current property is mutable and can hold any value, similar to an instance property on a class.

We can mutate the current property of “ref” inside the useEffect hook with the new state (which would still be the previous state when the button is clicked). And hence, we can keep track of the previous and current states.

Here’s putting it all together!

Like this article? Consider leaving a

Tip

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?