DEV Community

loading...

Using React Hooks "useState"

yahaya_hk profile image Yahaya Kehinde ・2 min read

Hooks came as a new addition in React 16.8 and they let us use state and other React features without writing a class component. In this article, we are going to be discussing the useState hook. This basically allows us use state within function components.

Within class components, in order to declare state, we would do the following:

Alt Text

And to update the state:

Alt Text

We could not use states outside class components. However using react hooks we can how use states within function components.

First we import useState from "react";

Then within the function component, we define our useState which returns two values, a variable for initialising the state and a function for updating state.

Alt Text

The syntax const [text, setText] = useState("") is how we use the useState hooks through ES6 destructuring to return two values

1) text which is how we initialise the state and is equivalent in function to state = {text: ""} and basically means we are initailising our state of text to an empty string.

2) setText is how we update the state using hooks and is eqivalent to
this.setState({text: "This is a state"}) and here we update the value of our state text to "This is a state".

In order to use our state, where the syntax would previously have been
<div>{this.state.text}</div>, using hooks, we can just call our state variable directly <div>{text}</div>

Alt Text

In summary, this destructed syntax using React hooks helps us to write cleaner and better code and helps us use state within function components.

Discussion (2)

pic
Editor guide
Collapse
plake492 profile image
Patrick Lake

On the import, you can also simply do this:

Import React, {useState} from "react "

this is especially nice when you start adding other hooks like useEffect, useReducer, etc.

Collapse
yahaya_hk profile image