React Hooks: useState

Chindalath Traymany
1 min readJun 10, 2021
Photo by Anne Nygård on Unsplash

With the addition of Hooks in React 16.8, we were blessed with the convenience of being able to use state and other React features without having to write a class, or converting our function components to class components. Instead, you can add state right into the function component! Let’s take a look at the examples shown on the docs.

Without Hooks

class Example extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}

With Hooks

import React, { useState } from 'react';

function Example() {
// Declare a new state variable, which we'll call "count"
const [count, setCount] = useState(0);

We declare a new variable and name it after the state we want to keep track of, and declare a second variable that will set its state: const [count, setCount]

Then, we set it to useState, a method that we have access to through importing { useState }. useState then takes in the default value of our count as an argument: useState(0).

Now, every time you would like to update the count, just call setCount!

For example:

//incrementsetCount(count + 1)

…and to read the current count, you can simply just call {count}:

<p>The count is currently {count}.</p>

--

--

Chindalath Traymany

Laotian-American woman pursuing my passion for mentally stimulating and complex problem-solving through programming.