Ohans Emmanuel Author, Understanding Redux. I Love God. I Love GF a little too much 💕🤣 http://thereduxjsbooks.com

React Hooks cheat sheet: Unlock solutions to common problems

5 min read 1656

While Hooks may have been the talk of the community for a while now, beyond the fuss, they do have a very simple API.

This article will highlight examples and use cases, from simple to advanced. I’ve also built an accompanying web app for live interaction with the examples herein.

Please note that this article includes a lot of code snippets and assumes some Hooks fluency. You may want to start here if you’re completely new to Hooks.

Let’s get started.


useState

useState lets you use local state within a function component. You can view the docs for it here and view a live, editable cheat sheet here.

Declare state variable

Declaring a state variable is as simple as calling useState with some initial state value.

useState(initialStateValue)
Simple usage of the useState hook.

Update state variable

Updating a state variable is as simple as invoking the updater function returned by the useState invocation.

const [stateValue, updaterFn] = useState(initialStateValue);

Note how the age state variable is being updated.
Here’s the code responsible for the screencast above.

Multiple state variables

Multiple state variables may be used and updated from within a functional component, as shown below:

Here’s the code responsible for the screencast above.

Use object state variable

As opposed to strings and numbers, you could also use an object as the initial value passed to useState.

Note that you have to pass the entire object to the useState updater function because the object is replaced, not merged.

setState vs. useState updater function.

Multiple state objects updated via a state object variable.
Here’s the code for the screencast above.

Initialize state from function

As opposed to just passing an initial state value, state could also be initialized from a function, as shown below:

Functional setState

The updater function returned from invoking useState can also take a function similar to the good ol’ setState:

const [value, updateValue] = useState(0)
// both forms of invoking "updateValue" below are valid 👇
updateValue(1);
updateValue(previousValue => previousValue + 1);

This is ideal when the state update depends on some previous value of state.

A counter with functional setState updates.
Here’s the code for the screencast above.

useEffect

useEffect accepts a function, which can perform any side effects. View the docs here, and check out the live, editable cheat sheet.

Basic side effect

Watch the title of the document update.
Here’s the code responsible for the screencast above.

Effect with cleanup

It’s pretty common to clean up an effect after some time. This is possible by returning a function from within the effect function passed to useEffect. Below is an example with addEventListener.

Multiple effects

Multiple useEffect calls can happen within a functional component, as shown below:

Note thatuseEffect calls can be skipped — i.e., not invoked on every render. This is done by passing a second array argument to the effect function.

Skipping effects (array dependency)

In the example above, useEffect is passed an array of one value: [randomNumber].

Thus, the effect function will be called on mount and whenever a new random number is generated.

Here’s the “Generate random number” button being clicked and the effect function being rerun upon generating a new random number:

Skipping effects (empty array dependency )

In this example, useEffect is passed an empty array, []. Therefore, the effect function will be called only on mount.

Here’s the button being clicked and the effect function not invoked:

Skipping effects (no array dependency)

Without an array dependency, the effect function will be run after every single render.

useEffect(() => {
console.log(“This will be logged after every render!”)
})

useContext

useContext saves you the stress of having to rely on a Context consumer. It has a simpler API when compared to MyContext.Consumer and the render props API it exposes. View the docs here, and view a live, editable cheat sheet.

The following example highlights the difference between consuming a context object value via useContext or Context.Consumer:

Here’s a live example with useContext:

Here’s the code responsible for the example above.

useLayoutEffect

useLayoutEffect has the very same signature as useEffect. We’ll discuss the difference between useLayoutEffect and useEffect below. Again, view the docs and the live, editable cheat sheet.

useLayoutEffect(() => {
//do something
}, [arrayDependency])

Similar usage as useEffect

Here’s the same example for useEffect built with useLayoutEffect:

Here’s the code responsible for the screencast above.

useLayoutEffect vs. useEffect

The function passed to useEffect fires after layout and paint, i.e., after the render has been committed to the screen. This is OK for most side effects that shouldn’t block the browser from updating the screen.

There are cases where you may not want the behavior useEffect provides, though; for example, if you need to make a visual change to the DOM as a side effect, useEffect won’t be the best choice.

To prevent the user from seeing flickers of changes, you can use useLayoutEffect. The function passed to useLayoutEffect will be run before the browser updates the screen.


useReducer

useReducer may be used as an alternative to useState. It’s ideal for complex state logic where there’s a dependency on previous state values or a lot of state sub-values.

Depending on your use case, you may find useReducer quite testable. View the docs and the live, editable cheat sheet.

Basic usage

As opposed to calling useState, call useReducer with a reducer and initialState, as shown below. The useReducer call returns the state property and a dispatch function.

Increase/decrease bar size by managing state with useReducer
Here’s the code responsible for the screencast above.

Initialize state lazily

useReducer takes a third function parameter. You may initialize state from this function, and whatever’s returned from this function is returned as the state object. This function will be called with initialState — the second parameter.

Same increase/decrease bar size — with state initialized lazily.
Here’s the code responsible for the screencast above.

Imitate this.setState’s behavior

useReducer uses a reducer that isn’t as strict as Redux’s. For example, the second parameter passed to the reducer, action, doesn’t need to have a type property.

This allows for interesting manipulations, such as renaming the second parameter and doing the following:

The results remain the same with a setState like api imitated.

useCallback

useCallback returns a memoized callback. View the docs and the view live, editable cheat sheet here.

Starter example

The following example will form the basis of the explanations and code snippets that follow.

In the example above, the parent component, <Age />, is updated (and re-rendered) whenever the “Get older” button is clicked.

Consequently, the <Instructions /> child component is also re-rendered because the doSomething prop is passed a new callback with a new reference.

Note that even though the Instructions child component uses React.memo to optimize performace, it is still re-rendered.

How can this be fixed to prevent <Instructions /> from re-rendering needlessly?

useCallback with referenced function

useCallback with inline function

useCallback also works with an inline function as well. Here’s the same solution with an inline useCallback call:


useMemo

useMemo returns a memoized value. View the docs and the live, editable cheat sheet.

Starter example

The following example will form the basis of the explanations and code snippets that follow.

Here’s the code responsible for the screenshot above.

The example above is similar to the one foruseCallback. The only difference here is that someValue is an object, not a string. Owing to this, the Instructions component still re-renders despite the use of React.memo

Why? Objects are compared by reference, and the reference to someValue changes whenever <App /> re-renders.

Any solutions?

Basic usage

The object someValue may be memoized using useMemo. This prevents the needless re-render.


useRef

useRef returns a “ref” object. Values are accessed from the .current property of the returned object. The.current property could be initialized to an initial value — useRef(initialValue), for example. The object is persisted for the entire lifetime of the component. Reference the docs and the live, editable cheat sheet.

Accessing the DOM

Consider the sample application below:

Accessing the DOM via useRef.
Here’s the code responsible for the screencast above.

Instance-like variables (generic container)

Other than just holding DOM refs, the “ref” object can hold any value. Consider a similar application below, where the ref object holds a string value:

Here’s the code responsible for the screencast above.

You could do the same as storing the return value from a setInterval for cleanup.

Other examples

Working on a near-real-world example can help bring your knowledge of Hooks to life. Until data fetching with React Suspense is released, fetching data via Hooks proves to be a good exercise for more Hooks practice.

Below’s an example of fetching data with a loading indicator:

Here’s the code responsible for the screencast above.

Conclusion

Hooks give a lot of power to functional components. I hope this cheat sheet proves useful in your day-to-day use of Hooks. Cheers!

Thanks to Hooks and a couple other new React features. Illustration by me 🙂

Plug: LogRocket, a DVR for web apps

LogRocket is a frontend logging tool that lets you replay problems as if they happened in your own browser. Instead of guessing why errors happen, or asking users for screenshots and log dumps, LogRocket lets you replay the session to quickly understand what went wrong. It works perfectly with any app, regardless of framework, and has plugins to log additional context from Redux, Vuex, and @ngrx/store.

In addition to logging Redux actions and state, LogRocket records console logs, JavaScript errors, stacktraces, network requests/responses with headers + bodies, browser metadata, and custom logs. It also instruments the DOM to record the HTML and CSS on the page, recreating pixel-perfect videos of even the most complex single-page apps.

Try it for free.

Ohans Emmanuel Author, Understanding Redux. I Love God. I Love GF a little too much 💕🤣 http://thereduxjsbooks.com

5 Replies to “React Hooks cheat sheet: Unlock solutions to common problems”

  1. Thanks, some interesting points on here. I’m currently building a single page app using React and WordPress and the hooks are proving very useful. I’m having problems persisting useState data with a route change, still looking for clues..!

  2. Nice! Typically, you’d have to centralize the data you want to share across routes – either via a centra store like redux’, or a central context object, or perhaps via the browser’s LocalStroage. You’ve got many options and the best for your specific use case depends on the application you’re building.

  3. I have a question: The official docs (and every blog post I’ve seen about hooks) says that fetching data should be done in useEffect. Changing the DOM “manually” with a reference to an element should be done in useLayoutEffect to avoid flicker. This seems like a contradiction to me. When you fetch data, 99% of the time you’re going to display some of that data in the UI. So you are indirectly (not manually with a reference to an element) changing the DOM. So, you’ll have a flicker if you do the fetch/state change in useEffect. So, why don’t all the docs say that fetching data should be standardly done in useLayoutEffect?

  4. Great article! I’m trying to set a random number to a color state using hooks:
    const COLOR = function() {
    return ‘#’ + Math.floor(Math.random() * 16777215).toString(16);
    };
    const [bgColor, setBgColor] = useState(COLOR);
    The value should be different every time the page is refreshed. In dev mode it’s working but when I build the app, the value become static. Would use “useEffect” for that case?

Leave a Reply