React Hooks Summarized

Codylillyw
5 min readFeb 23, 2023

And when to use them

This information is simply pulled directly from the react docs. I suggest looking there first for questions regarding react hooks. I have a small amount of the information here for quick reference of what each hook is. However the most recent docs have a great quick reference as well. More detail and examples can be found in the docs.

Before we start using hooks we need to know the rules around them otherwise we will quickly run into errors.

Rules of hooks

  • Hooks can only be called inside React function components.
  • Hooks can only be called at the top level of a component.
  • Hooks cannot be conditional

Common hooks

useState

Returns a stateful value and a function to update it by. Ordinary props are not changeable.

When to use it: useState is essential anytime you need to keep track of data that may change especially when it is used for in rendering.

useState() knows which component it is attached to, how to find the state information and how to trigger the re-rendering.

const [name, setName] = useState("Bob Ross")

You can create a useState hook from scratch like this:

// Example 0
function useState(initialValue) {
var _val = initialValue // _val is a local variable created by useState
function state() {
return _val // state() uses _val, declared by parent funciton
}
function setState(newVal) {
// same
_val = newVal // setting _val without exposing _val
}
return [state, setState] // exposing functions for external use
}
var [foo, setFoo] = useState(0) // using array destructuring
console.log(foo()) // logs 0 - the initialValue we gave
setFoo(1) // sets _val inside useState's scope
console.log(foo()) // logs 1 - new initialValue, despite exact same call

useEffect

useEffect handles updates/changes that must be based on the react lifecycle. I have an article here on how to avoid infinite rerenders when dealing with useEffect.

When to use it: Anytime you are needing to call something based on the react lifecycle such as mounting, updating state, and unmounting.

useContext

useContext is used to avoid prop drilling requiring a provider and giving to all children of said provider.

When to use it: When you need to pass data through several layers of components or when a set of changing data is reused throughout the application. People commonly use redux as an alternative but there are pros and cons to both approaches.

useReducer

When to use it: When you need to include more logic to determine how to set state.

useCallback

This is useful when passing callbacks to optimized child components that rely on reference equality to prevent unnecessary renders

useMemo

When to use it: Used to prevent state from unnecessarily reproducing expensive computations on renders.

useRef

Used to access a component or dom element such as to access its events or change it directly in some way.

forwardRef

Lets you expose a ref to a parent element. After using forwardRef on the child, setting it on an element, you can useRef to allow the parent to use it or pass it however is needed.

When to use it: Accessing the event data or other data that can only exist on the element such as for scrolling to a node, focusing a node, triggering an animation, selecting text, and so on.

Uncommon hooks

useImperativeHandle

Imperative vs Declarative

Imperative — Giving the computer a set of instructions to follow and the computer does what you want in an easy-to-follow sequence.

Declarative — A process of constantly defining what things are. Ask what we want first and declare them.

When to use it: Used to change how ref can be used such as adding custom functionality or limiting what can be used from the ref.

useInsertionEffect

When to use it: Used to insert styles before any dom mutations when working with CSS-in-JS.

useLayoutEffect

When to use it: To perform the layout measurements before the browser repaints the screen so you don't see a element moving after the screen has been rendered.

useDebugValue

When to use it: Used for logging data in React Devtools when using custom hooks.

useDeferredValue

When to use it: Used if you have an API call and want to handle the time period between the old value and when the new value arrives.

useTransition

When to use it: Transitions let you keep the user interface updates responsive even on slow devices.

With a transition, your UI stays responsive in the middle of a re-render. For example, if the user clicks a tab but then change their mind and click another tab, they can do that without waiting for the first re-render to finish.

useId

Used for generating a unique ID. This id is especially useful when you need to use serverside rendering.

When to use it: If you are mapping through a list of dynamic values you will get more performance using this hook since removing one item effects the index of everything else in the list. Alternatively you can use uuid library.

useSyncExternalStore

Possibly replace useSelector from react-redux as a way to get and set data from a store.

Custom hook

When to use it: When you have a set of state and logic that is reused between many different components. ie. a dropdown input hook

These custom hooks are built on top of existing hooks to provide specific shared functionality reducing duplicate code.

Example:

import React, { useState, useEffect } from 'react';

function FriendStatus(props) {
const [isOnline, setIsOnline] = useState(null);
useEffect(() => {
function handleStatusChange(status) {
setIsOnline(status.isOnline);
}
ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);
return () => {
ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);
};
});

if (isOnline === null) {
return 'Loading...';
}
return isOnline ? 'Online' : 'Offline';
}

References

How to Create a Custom React Hook and Publish it to npm (freecodecamp.org)

5 top React Hooks libraries compared — LogRocket Blog

Imperative vs Declarative Programming — the Difference Explained in Plain English (freecodecamp.org)

5 top React Hooks libraries compared — LogRocket Blog

Hooks API Reference — React (reactjs.org)

How to Build Your Own React Hooks: A Step-by-Step Guide (freecodecamp.org)

Deep dive: How do React hooks really work? (netlify.com)

--

--

Codylillyw

I am a Software engineering student in my senior year with most of my experience in web development and related technology.