DEV Community

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

Posted on • Updated on

React: useState and useEffect


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]


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.

import React from 'react';

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


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:

.then(r => r.json())
}, [])

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.

  4. 5.

Top comments (0)