Home / Blogs

What is useState Hook in React & How to Manage State in Functional Components?

React JS
·

October 4, 2023

what-is-usestate-hook-in-react

React Hooks revolutionized the way we build React applications by allowing us to use state and other React features without writing class components. One of the most fundamental and widely used hooks is useState.

In this blog, we will take an in-depth look at the useState hook, understand its purpose, and demonstrate how to manage state in functional components using this powerful hook.

What is the useState Hook?

The useState hook is a function provided by React that enables functional components to hold and update state, just like class components with ‘this.state’. With useState, you can add stateful behavior to functional components without converting them into classes.

Syntax of useState Hook:

const [state, setState] = useState(initialState);

Here, state represents the current value of the state, and setState is a function to update the state. initialState is the initial value of the state, which can be a primitive type (e.g., string, number, boolean) or an object.

To read more about what is React, refer to our blog What is React? A Beginner’s Guide to JavaScript Library

Using useState in a Functional Component

Let’s dive into a practical example to illustrate how to use the useState hook. Consider a simple functional component that displays a button and a counter. When the button is clicked, the counter should increment by one.

import React, { useState } from 'react';

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

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

  return (
    <div>
      <h2>Counter App</h2>
      <p>Count: {count}</p>
      <button onClick={handleIncrement}>Increment</button>
    </div>
  );
};

export default Counter;

In the code above, we imported the useState hook from React. Inside the Counter component, we called useState(0) to initialize our count state with an initial value of 0. The useState hook returns an array with two elements: the current value of the state (count in this case) and a function to update the state (setCount).

Updating State with ‘setState’

To update the state, you simply call the state updater function (setCount in this example) with the new value you want to set. React will then re-render the component with the updated state value. It’s important to note that calling setState does not merge the updated state with the previous state (as it did in class components). Instead, it replaces the old state entirely.

Handling Complex State

In addition to primitive types, the useState hook can also manage more complex state, such as objects or arrays. Let’s extend our Counter component to include a user profile with a name and age.

import React, { useState } from 'react';

const Profile = () => {
  const [profile, setProfile] = useState({
    name: 'John Doe',
    age: 30,
  });

  const handleAgeIncrement = () => {
    setProfile({ ...profile, age: profile.age + 1 });
  };

  return (
    <div>
      <h2>User Profile</h2>
      <p>Name: {profile.name}</p>
      <p>Age: {profile.age}</p>
      <button onClick={handleAgeIncrement}>Increment Age</button>
    </div>
  );
};

export default Profile;

In this example, we initialized the profile state with an object containing the name and age. When the “Increment Age” button is clicked, we use the spread operator (…) to create a copy of the profile object and update only the age property, leaving the name unchanged. This approach ensures that we don’t lose any existing data in the state when updating it.

To read more about integrating Django with React, refer to our blog How to Integrate Django With React in 2023

Conclusion

The useState hook is a fundamental tool in React that allows us to introduce stateful behavior into functional components easily. It simplifies state management and enables us to build complex applications using functional components without the need for class components. In this blog, we explored the syntax of useState, its usage in managing state, and how it can handle both primitive and complex state values.

By mastering the useState hook, you can take full advantage of the benefits of functional components in React and build more scalable and maintainable applications.

Horilla Editorial Team Author

Horilla Editorial Team is a group of experienced writers and editors who are passionate about HR software. We have a deep understanding of the HR landscape and are committed to providing our readers with the most up-to-date and informative content. We have written extensively on a variety of HR software topics, including applicant tracking systems, performance management software, and payroll software etc. We are always looking for new ways to share our knowledge with the HR community. If you have a question about HR software, please don't hesitate to contact us.