ch-12 Understanding useState React Hook

2 May 2024

ch-12 Understanding useState React Hook

The useState hook is one of the fundamental hooks provided by React, enabling functional components to have a state. Before hooks were introduced in React 16.8, state management was only possible within class components. Now, with useState, you can manage state in functional components, making them more versatile and powerful.


What is useState?

The useState hook allows you to add state to functional components. It returns an array containing two elements: the current state value and a function to update that state. This hook can be used multiple times within a single component to manage multiple state variables.


How to Use useState


Basic Usage

Here's a simple example to demonstrate how useState works:


import React, { useState } from 'react';


const Counter = () => {

 // Declare a state variable 'count' and a function 'setCount' to update it

 const [count, setCount] = useState(0);


 return (

  <div>

   <p>Count: {count}</p>

   <button onClick={() => setCount(count + 1)}>Increment</button>

  </div>

 );

};


export default Counter;


In this example:

  • useState(0) initializes the state variable count with a value of 0.
  • setCount is a function that updates the state variable count.
  • Clicking the button increments the count by 1.


Initial State

The initial state can be any value, including objects, arrays, or even functions. Here’s an example with an object:


import React, { useState } from 'react';


const UserProfile = () => {

 const [user, setUser] = useState({

  name: 'John Doe',

  age: 30,

  job: 'Developer'

 });


 return (

  <div>

   <h1>{user.name}</h1>

   <p>Age: {user.age}</p>

   <p>Job: {user.job}</p>

  </div>

 );

};


export default UserProfile;


Updating State

When updating state, it’s crucial to understand that calling the state updater function does not merge the new state with the old state. Instead, it replaces the old state. Therefore, when working with objects or arrays, you must explicitly merge the state.


Updating an Object

const updateUser = () => {

 setUser((prevState) => ({

  ...prevState,

  age: prevState.age + 1

 }));

};


Updating an Array

const addItem = (newItem) => {

 setItems((prevItems) => [...prevItems, newItem]);

};


Example: Todo List

Let’s build a simple Todo List to demonstrate useState in action:


import React, { useState } from 'react';


const TodoList = () => {

 const [todos, setTodos] = useState([]);

 const [input, setInput] = useState('');


 const addTodo = () => {

  if (input.trim()) {

   setTodos([...todos, input]);

   setInput('');

  }

 };


 return (

  <div>

   <h1>Todo List</h1>

   <input

    type="text"

    value={input}

    onChange={(e) => setInput(e.target.value)}

   />

   <button onClick={addTodo}>Add Todo</button>

   <ul>

    {todos.map((todo, index) => (

     <li key={index}>{todo}</li>

    ))}

   </ul>

  </div>

 );

};


export default TodoList;


In this example:

  • We maintain two pieces of state: todos (an array of todo items) and input (the current value of the input field).
  • The addTodo function adds the current input value to the todos array and clears the input field.


Conclusion

The useState hook is a versatile and essential tool for managing state in functional React components. By understanding how to initialize, update, and manipulate state using useState, you can build dynamic and interactive user interfaces. As you become more comfortable with useState, you'll find that it opens up many possibilities for state management within your React applications.


Notes and Source Code