DEV Community

Cover image for An introduction to React's usestate hook
Ishan Tiwari
Ishan Tiwari

Posted on

An introduction to React's usestate hook

If you use React you must be knowing that there is a concept of state and props. You can add state to a class component very easily but for adding state in a functional component you need to use the usestate hook.

What is a hook ?

Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class.

This is a quote from the official react documentation.

Hooks basically allow you to use methods which you can use in classes to be used in functional components. Hooks have some rules as well which we will discuss later on.
For now you just take way that hooks are utility functions which allow you to write the code that you can write in class components to be used in functional components.

The useState hook

In the useState hook you just import a function and then call it

import React, {useState} from 'react'
const App = () => {
 const initialCounter = 0
 const hookhere = useState(initialCounter)
 console.log(hookhere)
 return (<></>)
}
Enter fullscreen mode Exit fullscreen mode

As you can see the useState hook takes the initalCounter as a parameter.
The output of this function will be a list with the the first item as the state itself and the second item will be function to change the state. So, we can use object destructuring.
Like this

const [counter, setCounter] = useState(initialCounter)
Enter fullscreen mode Exit fullscreen mode

Now you can use this counter in the project.

Manipulating the State

You currently have a setState function you can use that to manipulate the state. It takes another function as a paramter and that function will be changing the state.

This function can take in the prevstate as a paramete r however this is optional.

setCounter((prevstate)=> {return prevstate + 1})
Enter fullscreen mode Exit fullscreen mode

As you can see here in this code above, the setCounter function takes in another function and that another function returns a value which becomes the new state.

Rules of hooks

Hooks have a few rules as well such as.

  1. You cannot call a hook conditionally
  2. Hooks must be called in the same order after every render.

Here is a codesandbox for a basic counter application using react hooks.

Discussion (0)