React Hooks: useState

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>

--

--

--

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

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Chindalath Traymany

Chindalath Traymany

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

More from Medium

State in React

How to style React

Conceptualizing React Components

React Context api in React-Native

Theme toggle with react context