React JS useState Hook


The useState hook is one of the fundamental hooks in React, introduced in React 16.8 as part of the Hooks API. It allows functional components to manage state, enabling them to hold and update data across renders.

Key Concepts of useState

  1. Basic Usage:

    • useState is used to declare state variables in functional components. It returns an array with two elements:
      • The current state value.
      • A function to update that state.
    • Syntax:
      const [state, setState] = useState(initialState);
    • Example:
      import React, { useState } from 'react'; function Counter() { const [count, setCount] = useState(0); // Declare state variable `count` return ( <div> <p>Count: {count}</p> <button onClick={() => setCount(count + 1)}>Increment</button> </div> ); }
  2. Initial State:

    • The initialState parameter in useState is used to set the initial value of the state. It can be any type of value: a number, string, object, array, etc.
    • Example:
      function Form() { const [inputValue, setInputValue] = useState(''); // Initial state as an empty string return ( <input type="text" value={inputValue} onChange={(e) => setInputValue(e.target.value)} /> ); }
  3. State Update Function:

    • The state update function returned by useState is used to update the state value. It can be called with a new state value or with a function that receives the current state and returns the new state.
    • Example:
      function Counter() { const [count, setCount] = useState(0); // Using function to update state const increment = () => setCount(prevCount => prevCount + 1); return ( <div> <p>Count: {count}</p> <button onClick={increment}>Increment</button> </div> ); }
  4. Handling Multiple States:

    • You can use multiple useState calls to manage different pieces of state within a single component. Each call to useState returns a separate piece of state and its update function.
    • Example:
      function UserProfile() { const [name, setName] = useState('Alice'); const [age, setAge] = useState(25); return ( <div> <p>Name: {name}</p> <p>Age: {age}</p> <button onClick={() => setName('Bob')}>Change Name</button> <button onClick={() => setAge(age + 1)}>Increase Age</button> </div> ); }
  5. State with Objects and Arrays:

    • When managing objects or arrays as state, ensure to update the state immutably. You should create new copies of the state object or array when making updates.

    • Example with Object:

      function UserProfile() { const [user, setUser] = useState({ name: 'Alice', age: 25 }); const updateName = (newName) => { setUser(prevUser => ({ ...prevUser, name: newName })); }; return ( <div> <p>Name: {user.name}</p> <p>Age: {user.age}</p> <button onClick={() => updateName('Bob')}>Change Name</button> </div> ); }
    • Example with Array:

      function TaskList() { const [tasks, setTasks] = useState(['Task 1', 'Task 2']); const addTask = (newTask) => { setTasks(prevTasks => [...prevTasks, newTask]); }; return ( <div> <ul> {tasks.map((task, index) => ( <li key={index}>{task}</li> ))} </ul> <button onClick={() => addTask('New Task')}>Add Task</button> </div> ); }
  6. Functional Updates:

    • When updating state based on its previous value, it's often better to use a functional update to avoid issues with stale state.
    • Example:
      function Counter() { const [count, setCount] = useState(0); const increment = () => { setCount(prevCount => prevCount + 1); }; return ( <div> <p>Count: {count}</p> <button onClick={increment}>Increment</button> </div> ); }

Summary

  • Declaring State: Use useState to declare state variables in functional components. It returns the current state and a function to update it.
  • Initial State: The initialState parameter sets the initial value for the state.
  • Updating State: Use the state update function to change the state. You can pass a new state value or a function that computes the new state.
  • Multiple States: Use multiple useState calls to manage different pieces of state in the same component.
  • Immutable Updates: When working with objects or arrays, ensure to update state immutably by creating new copies of the data.
  • Functional Updates: Use functional updates when updating state based on its previous value to ensure accurate state changes.

The useState hook provides a powerful way to manage state in functional components, making it easier to build interactive and dynamic React applications.