DEV Community

Cover image for React: useState and useEffect
Kevin O'Shaughnessy
Kevin O'Shaughnessy

Posted on • Updated on

React: useState and useEffect

Intro

React is a way of using JavaScript in an efficient and straightforward way, separating the code into different component files. It is used to build web applications. Officially, it is defined as "A JavaScript library for building user interfaces."[1] Two of the most important basic React hooks are useState and useEffect. useState allows one to add and update a state variable.[2] useEffect allows for performing side effects and also allows one to synchronize a component with an external system.[3]

useState

State in React is dynamic and can change overtime. It is effectively the default value when a component mounts. Each component maintains its own state but only sets the initial state for its children.[4] In React, there is a clear basic hierarchy of parent component(s) and children. The parents pass props - properties - to the children. Props cannot be changed by the components themselves but are passed to children by parent components.

from:
import React from 'react';

to:
import React, { useState } from 'react';

In order to actually use useState, it has to be imported into the component in which it is being used, as show above. useState will be imported in parentheses (so will useEffect, as we shall see).
The setup in the actual function will look something like this:

function App() {

const [quotes, setQuotes] = useState([])

//rest of code
}

The convention here is to start with the initial state, then the way to update that initial state: ex: state, setState. These 2 will go inside brackets and be set equal to the useState, which will have empty brackets. So useState is equal to the initial state and a function that updates the initial state.

Image description

useEffect

The above image is actually a great segue from useState to useEffect. Here, the useEffect is being used with a fetch and is using the function from our useState example. useEffect is great for doing things like fetching data or performing some side function. useEffect accepts 2 arguments and the second is actualyl optional.[5] Here, our useEffect looks like:

useEffect(()=>{
fetch('http://localhost:4000/data')
.then(r => r.json())
.then(setQuotes)
}, [])

But we can simplify it to useEffect(()=>{}, []) in order to clearly see the structure. The first part is the set up and the latter part has the optional dependencies. In my example, I just have an empty array. useEffect is used when interacting with something external, for side effects, and it cannot be used inside loops.


  1. https://legacy.reactjs.org/
  2. https://react.dev/reference/react/useState
  3. https://react.dev/reference/react/useEffect
  4. https://github.com/uberVU/react-guide/blob/master/props-vs-state.md 5.https://www.w3schools.com/react/react_useeffect.asp

Top comments (0)