useState Hooks


The useState hook is one of the most commonly used hooks in React. It allows functional components to manage state without the need for class components. The useState hook provides a way to add stateful behavior to functional components.

To use the useState hook, you need to import it from the 'react' package:

The useState hook takes an initial state value as its parameter and returns an array with two elements: the current state value and a function to update that state. The syntax for using useState is as follows:

Let's break down the useState hook:

1.state

This is the current state value. It can be any data type, such as a string, number, boolean, object, or array. You can initialize it with an initial value provided as the parameter to the useState function.


2. setState

This is the function that allows you to update the state value. When you call this function with a new value, it will trigger a re-render of the component with the updated state.

Here's an example of how to use the useState hook in a functional component:

In the above example, we initialize the state count to 0 using the useState hook. We also define two functions, increment and decrement, which update the state by calling setCount with the new value.

When the user clicks the "Increment" button, the increment function is called, and the count state is updated by adding 1. Similarly, when the "Decrement" button is clicked, the decrement function is called, and the count state is updated by subtracting 1. The updated state is then displayed in the JSX using the {count} syntax.

By using the useState hook, functional components can now have their own state, making them more powerful and flexible for managing dynamic data and triggering re-renders based on state changes.

In the next tutorial, we will talk about useEffect.

FAQs

Yes, you can use useState with custom Hooks. Custom Hooks can be created by extracting stateful logic into reusable functions. These custom Hooks can then use the useState Hook internally to manage state and return state variables and state update functions to the components that use them.

No, useState is a Hook and can only be used in functional components. Class components have their own state management using the this.state and this.setState methods.

Yes, you can use useState inside conditional statements or loops. Unlike the useState function call, conditional statements and loops are not hooks themselves, so you can use them inside any valid JavaScript block. However, make sure the Hooks are called at the top level of the component and not inside nested functions or conditions.