Image for post
Image for post

React Hooks: useState

Learn how to use state in a functional component.

What are Hooks?

With the introduction of Hooks in React 16.8 (released February 16, 2019), you can now use state in a functional component. These built-in functions “hook” into React’s state and lifecycle methods — no more complicated “this”, binding, passing state around in class components!

The 3 basic built-in hooks are useState, useEffect, and useContext. You can also write your own custom hooks to use state. In this post we’ll be focusing on the most useful hook, useState that will greatly simplify reading and writing code in React.

Use cases:

  • An array of items you want to buy in an e-commerce store
  • A string containing a color value that updates the background color
  • An integer holding a user’s score in a game

How to useState

// import the Hook
import React, { useState } from 'react';
// declare [current value, updated value] = use (initial value)const [state, setState] = useState(0);
const [active, setActive] = useState(false);
const [fruit, setFruit] = useState('');
const [form, setForm] = useState({
First: 'Bruce',
Last: 'Wayne',
Occupation: 'Philanthropist',
}]);

Just as state is set with an initial value in class components, useState sets the initial value of state. State can then be updated using the function setState. The update function can be called from an event handler or elsewhere.

Build a simple counter

One of the simplest ways to show how state changes is by incrementing a counter. Building a simple counter is a very common interview question because it demonstrates your knowledge of manipulating state and ability to manipulate the DOM through user interaction. I’ve included an example of updating a counter below, with comments to show what each line of code is doing, where state is set and updated.

// import React hook to use
import React, { useState } from 'react';
// create a function component
function Counter() {
// declare a new state variable, which we'll call "count"
// the initial value of count is set to 0
const [count, setCount] = useState(0);
// render component
return (
<div>
{/* initial count value = 0 */}
<p>You clicked {count} times</p>

{/* Each button click will update and increment count by 1 */}
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}

Resources

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