React Hooks 1: useState, useEffect, useContext, useRef & useReducer

Carolina Cobo
5 min readAug 2, 2022
Photo by Lautaro Andreani on Unsplash

I have been working in React for about nine months, and after finishing Brian’s Holt Complete Intro to React and Intermediate React and digging into the React Docs, I thought I would put together a summary of React Hooks and also my personal experience using some of them.

In this first part, I’ll cover useState, useEffect, useContext, useRef and useReducer, being the two first ones the ones use mostly at the moment.

Reusing state between components in React is hard. With Hooks, it’s possible to extract stateful logic from a component, this makes it possible to be tested independently and reused.

In conclusion, Hooks allow you to reuse stateful logic without changing your component hierarchy.

I’m going to list them all but first, I’ll go into more detail about the ones I use every day at work, useState and useEffect.

  1. useState

useState allows you to make components stateful. In older React to do so, it required using a class component. Hooks give the ability to write it using just functions.

This allows us to have more flexible components. In the example component below, every time the user clicks on the h1, it’ll change colours. It’s doing this by keeping that bit of state in a hook which is being passed that new value every render, so it always has and displays the latest state.

function Counter({initialCount}) {
const [count, setCount] = useState(initialCount);
return (
<>
Count: {count}
<button onClick={() => setCount(initialCount)}>Reset</button>
<button onClick={() => setCount(prevCount => prevCount - 1)}>-</button>
<button onClick={() => setCount(prevCount => prevCount + 1)}>+</button>
</>
);
}

2. useEffect

Compared to old React, Effects are how you recreate componentDidMount, componentDidUpdate, and componentDidUnmount.

Inside useEffect, you can do any sort of side effect action that you would have previously done in one of React's lifecycle methods. With it, you can fire API requests, integrate with third-party libraries (like jQuery), or do anything else that you need to happen on the side for your component.

--

--

Carolina Cobo

Frontend Software Engineer @ Genesys | Career switcher