Quantum Tech Newz Logo
HomeWhat’s NewAIReactJS

Understanding useState() hooks: simplifying with its usecases and scenarios

Last updated - 04 May, 2025, 10 minute reading

useState() : It is function use of declare "state variable" within your functional component. Think like that it is giving little memory to your component. This state can be anything like string, number, boolean and object, or even an array as well. When we change the state component rerender the to show the changes.

useState with different data types and common scenarios where you might use them:

1. Number State: Managing a Counter : When you need to display a numarical value that can be increment or decremented like a counter, a score or a quantity.


import React, { useState } from 'react';

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

  const increment = () => {
    setCount(count + 1);
  };

  const decrement = () => {
    setCount(count - 1);
  };

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={increment}>Increment</button>
      <button onClick={decrement}>Decrement</button>
    </div>
  );
}

export default Counter;

2. String State: Handling Text Input : When you need to capture and display text input from user such as in form fields.


import React, { useState } from 'react';

function TextInput() {
  const [name, setName] = useState('');

  const handleNameChange = (event) => {
    setName(event.target.value);
  };

  return (
    <div>
      <label>Enter Name: </label>
      <input type="text" value={name} onChange={handleNameChange} />
      <p>You entered: {name}</p>
    </div>
  );
}

export default TextInput;

3. Boolean State: Toggling Visibility or Status : When you need to control whether an element is shown or hidden, or track a simple on/off state.


import React, { useState } from 'react';

function Toggle() {
  const [isVisible, setIsVisible] = useState(false);

  const toggleVisibility = () => {
    setIsVisible(!isVisible);
  };

  return (
    <div>
      <button onClick={toggleVisibility}>
        {isVisible ? 'Hide' : 'Show'}
      </button>
      {isVisible && <p>Now you see me!</p>}
    </div>
  );
}

export default Toggle;

4. Object State: Managing Multiple Related Values : When you want to manage several related data togather, like user infomation or form data with multiple fields.

import React, { useState } from 'react';

function UserProfile() {
  const [user, setUser] = useState({
    firstName: 'John',
    lastName: 'Doe',
    age: 30,
  });

  const updateAge = () => {
    // Use the functional update to ensure you have the latest state
    setUser(prevUser => ({ ...prevUser, age: prevUser.age + 1 }));
  };

  const updateLastName = (newLastName) => {
    setUser(prevUser => ({ ...prevUser, lastName: newLastName }));
  };

  return (
    <div>
      <p>First Name: {user.firstName}</p>
      <p>Last Name: {user.lastName}</p>
      <p>Age: {user.age}</p>
      <button onClick={updateAge}>Increment Age</button>
      <button onClick={() => updateLastName('Smith')}>Change Last Name</button>
    </div>
  );
}

export default UserProfile;

Important Note for Object State : When updating object state, it's crucial to create a new copy of the object using the spread syntax (...prevObject) to avoid directly mutating the state. Direct mutation can lead to unexpected behavior and prevent React from correctly detecting changes.

5. Array State: Managing Lists of Items : When you need display and manipulate a list of items, such as todo list, a list of users and a collection of products.


import React, { useState } from 'react';

function TodoList() {
  const [todos, setTodos] = useState(['Buy groceries', 'Walk the dog']);
  const [newTodo, setNewTodo] = useState('');

  const addTodo = () => {
    if (newTodo.trim() !== '') {
      setTodos([...todos, newTodo]); // Create a new array with the new item
      setNewTodo('');
    }
  };

  const removeTodo = (indexToRemove) => {
    setTodos(todos.filter((_, index) => index !== indexToRemove)); // Create a new array without the removed item
  };

  return (
    <div>
      <h2>Todo List</h2>
      <ul>
        {todos.map((todo, index) => (
          <li key={index}>
            {todo} <button onClick={() => removeTodo(index)}>Remove</button>
          </li>
        ))}
      </ul>
      <input
        type="text"
        value={newTodo}
        onChange={(e) => setNewTodo(e.target.value)}
        placeholder="Add new todo"
      />
      <button onClick={addTodo}>Add Todo</button>
    </div>
  );
}

export default TodoList;

Important Note for Array State : Similar to object state, when updating arrays (adding, removing, or modifying elements), you should create a new array instead of directly modifying the existing one. Methods like ...spread, filter, map, and slice are your friends here.

6. State with a Function as Initial Value (Lazy Initialization) : The initial state value is expensive to compute, and you only want to compute it once when the component is first rendered.

import React, { useState } from 'react';

function ExpensiveComputation() {
  const [data, setData] = useState(() => {
    console.log('Expensive computation running...');
    // Simulate an expensive operation
    let result = 0;
    for (let i = 0; i < 1000000; i++) {
      result += i;
    }
    return result; // Initial state is the result of the computation
  });

  const updateData = () => {
    setData(prevData => prevData + 1);
  };

  return (
    <div>
      <p>Data: {data}</p>
      <button onClick={updateData}>Update Data</button>
    </div>
  );
}

export default ExpensiveComputation; 

In this case, the function passed to useState will only be executed during the initial render. Subsequent renders will reuse the existing state value.

These examples cover the most common data types you'll manage with useState and illustrate typical scenarios where each type is useful. Remember that useState is a powerful tool for making your functional components interactive and dynamic!


Sudhir Yadav, Senior Software Engineer