Jobs
Blogs
Courses
Mentorship
Partners
For Employers
e2e logo

React (How to use usestate hook and update state)

mac

REACT USESTATE HOOK:

  • The React useState Hook allows us to track state in a function component.
  • State generally refers to data or properties that need to be tracking in an application.

Import useState:


Intialize the useState:

We initialize our state by calling useState in our function component.

useState accepts an initial state and returns two values:

  • The current state.
  • A function that updates the state.

Example:

  • The first value, color, is our current state.
  • The second value, ,setColor is the function that is used to update our state.
  • Lastly, we set the initial state to an empty string: useState("") 

Read State:

Example:


Update State:

  • To update our state, we use our state updater function.
    Example: