UseState and UseEffect with React

Justin Tollison
Programmer’s Journey
4 min readMar 25, 2022

--

Whew, it’s been a couple months since our last blog post when we did an API call with fetch() and Javascript! This time around, we’re building a project within the React Framework or technology. It’s all very exciting and today, I’ll be writing about two important hooks within React that you’ll be using, useState and useEffect!

So, what are useState and useEffect? Well, they’re special functions within the React framework that allow you to access or hook into React features. State and Effect are the hooks, and useState() and useEffect() are the functions that to use those hooks that allow the React features. React State and React Effect are only used within the React framework, but they are very strong tools and you will no doubt be using them in your programming journey!

Let’s start off with React State, what is State and why or how would I begin to use it? Well, State is a dynamic data type, it changes over time or when the user does something. Say you want to set a “count” for a counter, when the counter changes, the “count” state will change with it. Unlike props when they are passed down from a parent component such as App.js, State will change whereas props cannot. Below we are importing the useState hook into the component and then we are invoking the useState function within out Example() function. The syntax for setting state is as follows:

const [state, setState] = useState()

(useState returns a pair of values, the current state and a function to update it.)

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

In our current example, we are naming our new state variable “count” and the setter function for the state, “setCount,” we are then initializing it with a variable of 0. If we were to console.log(count), it would return the value 0. “setCount” is a function that we will use to update state or “count” and it will be reflected in our console.logs(). A common thing to do with the state setter function is to add some functionality to your React app, where the user clicks or does some event such as clicking a button counter.

<button onClick={() => setCount(count + 1)}>    Click me
</button>

Within our button element, there is an onClick arrow function, it takes the setCount function and calls it, taking the current state of count and adding “1” to the value. If we were to click the button once and console.log(count), the value would be 1 instead of 0. When we declare and change the state variable, React will remember the current value between re-renders, keeping the most recent one. This is a very powerful tool, especially if you plan to use state within different child components. You may set multiple state variables to handle different things, such as using state for age, fruits, or event a todo list. Using it for an integer, a string, or an array or object, state variables become a dynamic data type that is able to change and reflect in your application. A common use for State is to set data from an API in it, that way when the API data changes, state will change with it and mirror onto your application. This leads to our next React hook, useEffect.

To keep things simple, we will just be talking about useEffect in terms of using it for data fetching or to pull data from a public API using fetch()! The Effect hook allows you to perform side effects in your components, or essentially, running some additional code after React has updated the DOM. The main effect of your component is to update the DOM or change an element while the side effect might be something like making a network request or accessing data from a database. This is where our API call or data fetching comes in. We are able to use the Effect hook within our function component and call it in order to pull the data we need. As a side note, useEffect is called anytime the component is rendered. So we would render our DOM and then our useEffect would be called afterwards.

useEffect(() => { 
fetch(API)
.then((r) => r.json())
.then((data) => {
setState(data) });
}, []);

Here we are invoking the useEffect as an arrow function and calling a fetch() function in order to fetch data from an external API (or RESTful API). We are then going through the motions of taking the response, jsonifying the response and then setting that to the variable of data and using that data in our state setter function. We’re combining useEffect and useState essentially! Our state is now set to the data of the API we fetched, which in most cases is an array. There is one last bit at the end of the syntax of our useEffect, on the last line we have our closing curly brace and then two closed square brackets before ending the function. The [] at the end of our function tells React that we only want to initialize this useEffect once, if we didn’t tell it that, it would persist the useEffect functionality, change state and then re-render the application and it would repeat in an infinite loop. This wouldn’t be ideal as we’d be calling the API continuously and reach our limit of API calls.

There is a lot more to useEffect, such as effects with and without cleanup, but we won’t be going over those today. And I am sure there is much more to useState, but I am content to cover only the basics today. I hope this was helpful and thank you for reading, good luck on continuing your programming journey and be well!

--

--

Justin Tollison
Programmer’s Journey

Unity Game Developer and Flatiron Software Engineering Alumni