ReactJS hooks essentials Part 1: useState and setState

Daniel Patnode
2 min readDec 10, 2020

--

The incorporation of state values is essential for any react developer to understand in order to make fully flushed out interactive web applications. React hooks give developers a cleaner, tighter and more direct way to implement use of state. In this article I’ll go over a simple application that allows users to display their status based off of button clicks using hooks built in useState and setState functions. The status is going to be a state value that represents the current status for this application.

To start out we’ll need to set up a functional component like so:

starting functional component

Which renders this:

initial render

The next step is to incorporate the useState hook from the react library like so:

import React, { useState } from "react";
//add this on line 2 in place of what was there before

*Sidenote*:
What is useState? It’s a hook.
A hook? A hook is a function that allows you to add further functionality to a component. React has a several built in hooks (like useState) to handle state changes within applications.

Next, create a constant and use some array destructuring for the status value, passing “open” as the initial state for the application. When the app loads the status will be set to open.

Initial state is set with useState to “Open”

useState returns a pair, right now status is the state value that was given the name “status”. The second value returned by useState is a function used to update the state. Naming conventions dictate that this second value should be named so that the word set comes before what ever the initial value of state was, in this case status. Add setStatus to the array destructuring, like so:

const [status, setStatus] = useState("Open");
//line 6

the setStatus function can now be utilized to change the status. adding several buttons with onClicks pointing to the setStatus function with different values associated will change the status set in state to whatever is clicked:

State being changed on button clicks.

Hooks, like useState and setState, give developers the ability to seamlessly alter state and build out interactive components with ease. there are plenty of other built in hook functions that you can checkout here.

--

--