Mapagam
  • JavaScript 
  • Web APIs 
  • TypeScript 
  • React 

How to Use the useState Hook in React (With Simple Examples)

Posted on April 9, 2025 • 7 min read • 1,290 words
Share via
Mapagam
Link copied to clipboard

Learn how to use the `useState` hook in React with simple examples, and manage state in functional components efficiently.

On this page
1. Introduction to the useState Hook 1.1. What is useState? 1.2. Why Use the useState Hook? 2. How to Use useState with Simple Examples 2.1. Basic Example: Counter Application 2.1.1. Explanation 2.2. Example 2: Toggling a Boolean Value 2.2.1. Explanation 2.3. Example 3: Managing Form Inputs 2.3.1. Explanation 3. Advanced Use of useState Hook 3.1. Using Objects and Arrays with useState 3.2. Using Functional Updates in setState 3.3. Delayed State Updates 4. Best Practices for Using the useState Hook 5. Conclusion

React has transformed the way developers build user interfaces by offering a component-based architecture that encourages reusability and maintainability. One of the most important features in React is the useState hook. It allows developers to add state to functional components, making it possible to manage dynamic content in a seamless way. If you’re new to React or just getting started with hooks, understanding how to use the useState hook is essential for building interactive applications.

1. Introduction to the useState Hook

React introduced hooks in version 16.8 to help developers manage state and side effects in functional components. Prior to hooks, state management was only possible in class components. However, with the advent of hooks like useState, functional components now have the same capabilities as class components.

1.1. What is useState?

The useState hook is a function that allows you to add state to a functional component in React. It returns an array with two elements: the current state value and a function to update that state. Here’s the syntax:

const [state, setState] = useState(initialState);
  • state: The current value of the state variable.
  • setState: A function used to update the state value.
  • initialState: The initial value for the state variable, which can be a primitive value, an object, an array, or even a function.

1.2. Why Use the useState Hook?

Before hooks, React developers had to use class components to handle state, which could lead to complex code and lengthy boilerplate. With useState, functional components can handle state without needing to be rewritten as class components, making them more concise and easier to manage.

The useState hook also enables features such as:

  • Simplified code: Managing state in a functional component is more straightforward and less verbose.
  • Reusability: Functional components with hooks are often easier to reuse in different parts of the application.
  • Better performance: By keeping components as functional, React optimizes the re-rendering process, improving overall app performance.

2. How to Use useState with Simple Examples

Now that we have an understanding of what the useState hook is and why it’s important, let’s dive into how to use it in a React application with a few simple examples.

2.1. Basic Example: Counter Application

The most common example used to demonstrate useState is a counter application, which increments or decrements a value based on user interactions. Let’s create a simple counter component using useState.

import React, { useState } from 'react';

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

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

export default Counter;

2.1.1. Explanation

  • We initialize the count state to 0 using useState(0).
  • The setCount function is used to update the value of count.
  • When the “Increment” button is clicked, the count state is updated by adding 1, and when the “Decrement” button is clicked, it is decreased by 1.

This example shows how to easily add interactive behavior to a functional component with the useState hook.

2.2. Example 2: Toggling a Boolean Value

Another common scenario for using useState is toggling a boolean value, such as showing or hiding content. Here’s an example where we toggle the visibility of a text paragraph.

import React, { useState } from 'react';

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

  return (
    <div>
      <button onClick={() => setIsVisible(!isVisible)}>Toggle Text</button>
      {isVisible && <p>This is a toggled text!</p>}
    </div>
  );
}

export default ToggleText;

2.2.1. Explanation

  • We initialize isVisible state as false, which means the paragraph is initially hidden.
  • On button click, the setIsVisible function toggles the boolean value by using !isVisible.
  • The paragraph <p>This is a toggled text!</p> is only rendered when isVisible is true.

This is a common pattern for toggling between two states, such as showing and hiding elements on the page.

2.3. Example 3: Managing Form Inputs

A common use case for the useState hook is managing the state of form inputs. Let’s create a simple form that accepts a user’s name and displays it after submission.

import React, { useState } from 'react';

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

  const handleSubmit = (e) => {
    e.preventDefault();
    alert(`Hello, ${name}`);
  };

  return (
    <div>
      <form onSubmit={handleSubmit}>
        <input
          type="text"
          value={name}
          onChange={(e) => setName(e.target.value)}
          placeholder="Enter your name"
        />
        <button type="submit">Submit</button>
      </form>
    </div>
  );
}

export default UserForm;

2.3.1. Explanation

  • The name state holds the value of the input field.
  • When the user types into the input field, the onChange event handler calls setName to update the state with the new value.
  • On form submission, the handleSubmit function shows an alert with the entered name.

This example shows how useState can be used to manage form data in React components.

3. Advanced Use of useState Hook

While the examples above demonstrate basic usage of the useState hook, there are more advanced features and techniques to explore.

3.1. Using Objects and Arrays with useState

The useState hook is not limited to primitive types like numbers and strings. You can also use it to store objects or arrays. However, when dealing with objects or arrays, you need to be careful not to mutate the state directly, as React will not trigger a re-render if the state is mutated in place.

Example: Using an Object with useState

import React, { useState } from 'react';

function UserProfile() {
  const [user, setUser] = useState({ name: '', age: '' });

  const handleInputChange = (e) => {
    const { name, value } = e.target;
    setUser((prevUser) => ({
      ...prevUser,
      [name]: value,
    }));
  };

  return (
    <div>
      <input
        type="text"
        name="name"
        value={user.name}
        onChange={handleInputChange}
        placeholder="Name"
      />
      <input
        type="text"
        name="age"
        value={user.age}
        onChange={handleInputChange}
        placeholder="Age"
      />
      <p>Name: {user.name}</p>
      <p>Age: {user.age}</p>
    </div>
  );
}

export default UserProfile;

Explanation:

  • In this example, we initialize the user state as an object with name and age properties.
  • The handleInputChange function updates the corresponding property in the object by creating a new object using the spread operator (...prevUser) and modifying the specific property.

3.2. Using Functional Updates in setState

When updating state based on the previous state, it’s a good practice to use the functional update form of setState. This ensures that the state is always updated based on the most current value.

setCount((prevCount) => prevCount + 1);

3.3. Delayed State Updates

The state update in React is asynchronous. This means that if you try to immediately log the updated state right after calling setState, you’ll still get the old value. To work around this, you can use the useEffect hook to track state changes.

4. Best Practices for Using the useState Hook

While the useState hook is a powerful tool, there are a few best practices you should keep in mind:

  • Avoid mutating state directly: Always use the setter function returned by useState to update the state. Mutating the state directly can cause issues with re-renders and may lead to bugs.
  • Use state initialization functions wisely: If you need to calculate the initial state based on a more complex calculation, you can pass a function to useState instead of an initial value.
const [count, setCount] = useState(() => expensiveCalculation());
  • Keep state updates minimal: Avoid overcomplicating your state management. It’s often better to break down your component into smaller pieces that manage their own state, especially if state values don’t depend on each other.

5. Conclusion

The useState hook is an essential part of React that allows you to add state management to functional components. Whether you’re building simple counter applications, handling form inputs, or managing more complex data structures, useState provides a flexible and efficient way to manage state in your React app.

By following best practices, understanding how to manage different types of data, and staying aware of how React batches state updates, you can use useState to build dynamic, interactive applications with ease.

UseState Hook   React Tutorial   React Hooks   Functional Components   State Management in React  
UseState Hook   React Tutorial   React Hooks   Functional Components   State Management in React  
 React useEffect Hook Explained for Beginners (With Examples)
React Hooks vs. Class Components: Which One Should You Use? 

More Reading!

  1. Beginner’s Guide to JavaScript Functions (With Best Practices)
  2. Understanding useState in React: A Beginner-Friendly Guide
  3. Understanding JavaScript Hoisting Without Confusion
  4. React Event Handling: A Beginner’s Guide to onClick, onChange & More
  5. How to Create Your First React Component (With Example Code)
On this page:
1. Introduction to the useState Hook 1.1. What is useState? 1.2. Why Use the useState Hook? 2. How to Use useState with Simple Examples 2.1. Basic Example: Counter Application 2.1.1. Explanation 2.2. Example 2: Toggling a Boolean Value 2.2.1. Explanation 2.3. Example 3: Managing Form Inputs 2.3.1. Explanation 3. Advanced Use of useState Hook 3.1. Using Objects and Arrays with useState 3.2. Using Functional Updates in setState 3.3. Delayed State Updates 4. Best Practices for Using the useState Hook 5. Conclusion
Follow me

I work on everything coding and technology

   
Mapagam
Mapagam is your go-to resource for all things related to frontend development. From the latest frameworks and libraries to tips, tutorials, and best practices, we dive deep into the ever-evolving world of web technologies.
Licensed under Creative Commons (CC BY-NC-SA 4.0).
 
Frontend
JavaScript 
Web Api 
TypeScript 
React 
Social
Linkedin 
Github 
Mapagam
Code copied to clipboard