DEV Community

Arun Kumar
Arun Kumar

Posted on

REACT USESTATE

Understanding useState in React

React is a powerful library for building user interfaces, and one of its most important features is the ability to manage state. In function components, state management is typically done using the useState hook. In this section, we’ll dive into what useState is, how to use it, and provide a complete example of a counter app built with React.

What is useState?

useState is a Hook that lets you add React state to function components. It allows you to store and update values that can change over time. When the state changes, React re-renders the component to reflect the updated state.

Syntax of useState

The useState hook is simple to use. It takes one argument, the initial state, and returns an array containing two elements:

  1. The current state value: This is the current value of the state.
  2. A function to update the state: This function is used to update the state value whenever necessary.

Here is the basic syntax:

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

Enter fullscreen mode Exit fullscreen mode
  • state: The current state value.
  • setState: The function to update the state.
  • initialState: The initial value of the state. This can be any data type—string, number, array, object, etc.

Top comments (0)