Open In App

Managing Complex State with useState

Managing the state in React applications is very important when you want to create dynamic and interactive user interfaces. In this article, we will be going to learn how we can use useState( A React Hook ) to manage the complex states in React applications we generally do it using the redux library of React ( Redux is a React library that allows us to manage to react complex state efficiently and cleanly).

What is useState Hook?

React useState() hook allows one to declare a state variable inside a function. It should be noted that one use of useState() can only be used to declare one state variable. It was introduced in version 16.8.

Importing React useState Hook:

To import the useState hook, write the following code at the top level of your component



import { useState } from "react";

Structure of React useState hook

This hook takes some initial state and returns two value. The first value contains the state and the second value is a function that updates the state. The value passed in useState will be treated as the default value

React useState Hook Syntax:

const [val, setVal] = useState(0);

What is Complex State Management ?

Sometime we need to manage different states in different components. Managing the different states changes in different components of react app is known as complex state management. More number of component in the react app makes the app more complex and it is difficult to manage the state between them which are common in many of the components.

To manage this state management there are many libraries that you can learn about it named Redux, Context API.

Now we will see how we can manage complex states using useState.

Steps to Create React Project

Step 1: Create a React Application by entering the Command.

npx create-react-app gfg

Step 2: After the Neccesary folders created, enter into the folder using command.

cd gfg

Step 3: Now Install the necessary dependencies using command

npm install

Step 4: You can see the current basic setup by running it using common

npm start

The update dependencies in package.json file will look like:

 "dependencies": {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
}

Examples of Complex State Management

Example 1: In this example we will handle the state of every input field of the form with the help of single useState

Folder Structure:

Example Code:




// App.js
 
import Form from "./Form/Form";
 
function App() {
    return (
        <div className="App">
            <Form />
        </div>
    );
}
 
export default App;




// Form/form.js
 
import React from 'react';
import useUserState from '../Form/common'
 
function Form() {
    const { Data, setData } = useUserState();
    const handleChange = (event) => {
        setData((prev) => ({
            ...prev,
            [event.target.name]: event.target.value,
        }))
    };
 
    const handleDetails = (event) => {
        setData((prev) => ({
            ...prev,
            details: {
                ...prev.details,
                [event.target.name]: event.target.value,
            }
        }))
    }
 
    const handleSubmit = (e) => {
        e.preventDefault();
        alert('Form Data Submitted');
    };
 
    return (
        <div >
            <form style={{ display: "flex", flexDirection: "column",
            width: "300px", gap: "20px", padding: "20px" }}>
                <label>
                    Username:
                </label>
                <input type="text" name="username" value={Data.details.username}
                    onChange={handleDetails} />
                <label>
                    Email:
                </label>
                <input type="email" name="email" value={Data.email}
                    onChange={handleChange} />
                <label>
                    Password:
                </label>
                <input type="password" name="password" value={Data.password}
                    onChange={handleChange} />
                <label>
                    Age:
                </label>
                <input type="number" name="age" value={Data.details.age}
                    onChange={handleDetails} />
                <button type="submit" onClick={handleSubmit}>Submit</button>
            </form>
        </div>
    );
}
 
export default Form;




// Form/common.js
 
import { useState } from 'react';
 
const useUserState = () => {
 
    const [Data, setData] = useState({
        email: '',
        password: '',
        details: {
            username: '',
            age: '',
        }
    });
 
    return { Data, setData };
};
 
export default useUserState;

Output –

Example 2: In this example we are managing two counter at the same sime with the help of single useState.

Folder Structure:

Folder Structure

Example Code:




// App.js
 
import Counter from "./Counter/Counter";
 
function App() {
    return (
        <div className="App">
            <Counter />
        </div>
    );
}
 
export default App;




// Counter/Counter.js
 
import React from 'react';
import useUserState from './common'
 
function Counter() {
    const { items, setItems } = useUserState();
 
    const updateQuantity = (itemId, newQuantity) => {
        setItems((prevItems) =>
            prevItems.map((item) =>
                item.id === itemId ?
                    { ...item, quantity: newQuantity } : item
            )
        );
    };
 
    return (
        <div style={{ display: "flex", flexDirection: "column", gap: "10px" }}>
            <div>
                {items[0].quantity}
                <br />
                <button onClick={() => updateQuantity(items[0].id,
                    items[0].quantity + 1)}>Increase</button>
            </div>
            <div>
                {items[1].quantity}
                <br />
                <button onClick={() => updateQuantity(items[1].id,
                    items[1].quantity + 1)}>Increase</button>
            </div>
        </div>
    );
}
 
export default Counter;




// Counter/common.js
 
import { useState } from 'react';
 
const useUserState = () => {
 
    const [items, setItems] = useState([
        { id: 1, name: 'Nitin', quantity: 2 },
        { id: 2, name: 'Sneha', quantity: 4 },
    ]);
 
    return { items, setItems };
};
 
export default useUserState;

Output:


Article Tags :