DEV Community

Cover image for 5 Situations Where You Need useState in Your Projects
Golsa
Golsa

Posted on

5 Situations Where You Need useState in Your Projects

React's useState is one of the most essential hooks for managing state in functional components. If you’ve ever wondered when to use useState in your projects, this article highlights five practical situations where useState becomes necessary. Let's dive in!

1. Toggling UI Elements (e.g., Modals or Dropdowns)

Whenever you need to show or hide an element like a modal, dropdown, or tooltip, useState can help manage the visibility state.

import { useState } from 'react';

function Modal() {
  const [isOpen, setIsOpen] = useState(false);

  return (
    <div>
      <button onClick={() => setIsOpen(!isOpen)}>Toggle Modal</button>
      {isOpen && <div className="modal">This is a modal</div>}
    </div>
  );
}

Enter fullscreen mode Exit fullscreen mode

Here, useState tracks whether the modal is open (true) or closed (false).

2. Handling User Input in Forms
Managing form inputs, like text fields, checkboxes, or radio buttons, often requires maintaining the current value. useState is perfect for this.

function LoginForm() {
  const [username, setUsername] = useState('');

  return (
    <form>
      <label>
        Username:
        <input 
          type="text" 
          value={username} 
          onChange={(e) => setUsername(e.target.value)} 
        />
      </label>
      <p>Your username: {username}</p>
    </form>
  );
}

Enter fullscreen mode Exit fullscreen mode

Each keystroke updates the state, making the form interactive and responsive.

3. Tracking Component State (e.g., Counters)
useState is often used for tracking simple numeric states, like counters, scores, or progress indicators.

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

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
      <button onClick={() => setCount(count - 1)}>Decrement</button>
    </div>
  );
}

Enter fullscreen mode Exit fullscreen mode

This example shows a simple counter where useState stores the current count.

4. Managing Themes or Modes
For toggling themes (e.g., light mode and dark mode), useState can handle the current mode and trigger UI changes accordingly.

function ThemeSwitcher() {
  const [theme, setTheme] = useState('light');

  return (
    <div className={`theme-${theme}`}>
      <button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>
        Switch to {theme === 'light' ? 'dark' : 'light'} mode
      </button>
    </div>
  );
}

Enter fullscreen mode Exit fullscreen mode

With useState, you can easily track the active theme and update the styles dynamically.

5. Fetching Data and Storing Local Results
When fetching data from an API, you can store the results in a state variable for local use in your component.

import { useState, useEffect } from 'react';

function UserList() {
  const [users, setUsers] = useState([]);

  useEffect(() => {
    fetch('https://jsonplaceholder.typicode.com/users')
      .then((response) => response.json())
      .then((data) => setUsers(data));
  }, []);

  return (
    <ul>
      {users.map((user) => (
        <li key={user.id}>{user.name}</li>
      ))}
    </ul>
  );
}

Enter fullscreen mode Exit fullscreen mode

Here, useState holds the fetched user data, making it available for rendering.

Final Thoughts
useState is a fundamental hook in React that enables you to manage dynamic, interactive, and responsive states in functional components. By understanding these five common use cases, you can confidently integrate useState into your projects and handle state effectively.

What are your favorite use cases for useState? Share them in the comments below!

Top comments (1)

Collapse
 
parsasadr profile image
Parsa

What a useful article thanks!