useState for Managing State in Functional Components in React JS

In React, functional components have become more popular due to their simplicity and ease of use. With the introduction of Hooks in React 16.8, managing state in functional components has become straightforward, thanks to the useState hook. Before hooks, state management was only available in class components. Now, useState allows functional components to hold and update state, enabling developers to create dynamic and interactive UIs.

What is useState?

The useState hook is a fundamental hook in React that allows you to add state to a functional component. It returns an array with two elements:

  • State value: The current state value.
  • Set state function: A function that allows you to update the state.

The syntax of the useState hook is as follows:

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

Here, initialValue is the initial state, which can be any type, such as a number, string, array, or object.

Basic Example of useState

Let’s look at a simple example of how to use the useState hook in a functional component.

          
              import React, { useState } from 'react';

              function Counter() {
                  // Declare a state variable 'count' with an initial value of 0
                  const [count, setCount] = useState(0);

                  // Function to increment the count
                  const increment = () => {
                      setCount(count + 1); // Update the count state
                  };

                  return (
                      

Count: {count}

); } export default Counter;

In this example, we declare a state variable count with the initial value of 0 using useState(0). The setCount function updates the value of the state when the "Increment" button is clicked.

Updating State with useState

One important aspect of the useState hook is that it provides a function to update the state. When you call the state updater function (e.g., setCount), React will re-render the component with the new state value.

In the previous example, calling setCount(count + 1) updates the state, and React automatically re-renders the component to reflect the new value of count.

Working with Different Data Types in useState

Although the useState hook works with any data type, let's explore how it can be used with other types of data such as strings, arrays, and objects.

Using useState with Strings

If you want to store a string in the state, you can pass a string as the initial value to useState.

          
              import React, { useState } from 'react';

              function NameChanger() {
                  const [name, setName] = useState('John Doe');

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

                  return (
                      

Hello, {name}

); } export default NameChanger;

In this example, useState('John Doe') initializes the name state with a string. The setName function updates the name state when the input field value changes.

Using useState with Arrays

To manage arrays with useState, you can pass an array as the initial state.

          
              import React, { useState } from 'react';

              function TodoList() {
                  const [todos, setTodos] = useState([]);

                  const addTodo = (todo) => {
                      setTodos([...todos, todo]); // Adding a new todo item to the array
                  };

                  return (
                      

Todo List

    {todos.map((todo, index) => (
  • {todo}
  • ))}
); } export default TodoList;

Here, the todos state is an array that starts off empty. The addTodo function adds a new item to the array by spreading the current array and appending the new todo.

Using useState with Objects

For managing complex state structures, such as objects, you can use useState with an object as the initial state.

          
              import React, { useState } from 'react';

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

                  const updateAge = () => {
                      setUser({ ...user, age: user.age + 1 }); // Updating only the age in the object
                  };

                  return (
                      

{user.name}'s Profile

Age: {user.age}

); } export default UserProfile;

In this case, useState({ name: 'John', age: 30 }) initializes the user state with an object. The updateAge function updates only the age property of the object, while leaving the name intact.

Conclusion

The useState hook is an essential tool for managing state in functional components in React. It simplifies state management and makes functional components more powerful by allowing them to have local state. Whether you’re working with numbers, strings, arrays, or objects, the useState hook can be used to manage state efficiently. By using this hook, React developers can build dynamic and interactive applications without the need for class components.





Advertisement