Logo

dev-resources.site

for different kinds of informations.

Create a modified useState hook to get previous value

Published at
12/27/2023
Categories
webdev
react
hooks
usestate
Author
vvkkumar06
Categories
4 categories in total
webdev
open
react
open
hooks
open
usestate
open
Author
10 person written this
vvkkumar06
open
Create a modified useState hook to get previous value

In React Js, we use useState in almost every component. An example of useState is given below:

  const [count, setCount] = useState(0);
Enter fullscreen mode Exit fullscreen mode

In above example we have created a count state where we can use setCount to update the count. But, imagine a situation where you need to compare the previous count with current count ( i.e. count ).

In this tutorial, we will create a custom hook in which we will also get a third variable i.e. prevState

const [count, setCount, prevCount] = useStateModified(0);
Enter fullscreen mode Exit fullscreen mode

In above example, we have prevCount as well that we can use for our custom logic.

Step 1

Create a file in project directory with name useStateModified.jsx.

Step 2

Create a function with name useStateModified and export it as default export.

const useStateModified = () => {

};

export default useStateModified;

Enter fullscreen mode Exit fullscreen mode

Step 3

Create a state using useState, take initialState as parameter in our custom hook and return state and setState.

import { useState } from "react";

const useStateModified = (initalState) => {
  const [state, setState] = useState(initalState);
  return [state, setState];
};

export default useStateModified;
Enter fullscreen mode Exit fullscreen mode

Step 4

Till now it is nothing new and is equivalent to directly using useState in any component. To save the previous state we will use useRef hook. We will return prevState.current as third item of array.

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

const useStateModified = (initalState) => {
  const [state, setState] = useState(initalState);
  const prevState = useRef(initalState);

  return [state, setState, prevState.current];
};

export default useStateModified;
Enter fullscreen mode Exit fullscreen mode

Step 5

If you are aware of useRef, its value won't change until and unless we update its current property ( example - prevState.current = 'some value').
So now, we will write a useEffect hook that will listen for the changes in state value. Whenever there is a change in the state, we will also update prevState.

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

const useStateModified = (initalState) => {
  const [state, setState] = useState(initalState);
  const prevState = useRef(initalState);

  useEffect(() => {
    prevState.current = state;
  }, [state]);

  return [state, setState, prevState.current];
};

export default useStateModified;
Enter fullscreen mode Exit fullscreen mode

When there will be change in state, it will execute the line (return [state, setState, prevState.current]) before running useEffect statement.

Lets see how we can use it.

import { useEffect, useState } from "react";
import "./styles.css";
import useStateModified from "./useStateModified";

export default function App() {
  const [count, setCount, prevCount] = useStateModified(0);
  return (
    <div className="App">
      <button onClick={() => setCount((c) => c + 1)}>Increment</button>
      <h2>Count: {count}</h2>
      <h2>Previous Count: {prevCount}</h2>
    </div>
  );
}

Enter fullscreen mode Exit fullscreen mode

useStateModified

This way you can create custom useState hook to achieve functionality where you need previous state.

Check demo here

usestate Article's
30 articles in total
Favicon
useState e useEffect
Favicon
Mastering React's useState Hook: The Basics and Advanced Use Cases
Favicon
Understanding useState in TypeScript React
Favicon
A Beginner's Guide to useState in React
Favicon
Mastering React Hooks: useState and useEffect
Favicon
Managing State in react using different method, & understand batching
Favicon
Hooks Behind The Scenes 2, useState!!
Favicon
useState Hook Explained
Favicon
Exploring State Management in React: One-Way Data Binding, State Lift-Up, Prop Drilling, and Handling Complex States
Favicon
Diving into React.js
Favicon
What is useState?
Favicon
Avoiding Common useState() Mistakes in React
Favicon
Simplifying State Management in React with Zustand
Favicon
Having trouble with react component hooks...
Favicon
useState( )
Favicon
Create a modified useState hook to get previous value
Favicon
UseState why?
Favicon
Part 2 - Mastering the useState Hook
Favicon
Part 1 - Getting Started with React Hooks
Favicon
ugly useState
Favicon
Unlocking the Power of React Hooks
Favicon
Mastering 'useState' in React with TypeScript: 5 Different Use-Cases for 'useState'
Favicon
React.useRefの理解を含めるエクササイズ
Favicon
Toggle Feature for a Drop-down list on React using useState();
Favicon
useContext
Favicon
A Beginner's Guide to Using Fetch in React: Making Data Requests Made Easy
Favicon
Alterações de páginas de forma dinâmica com o UseState
Favicon
Stop using useState for everything
Favicon
useState: la caja de juguetes
Favicon
Detaylı React Hooks Kullanımı: useState

Featured ones: