Skip to content

Instantly share code, notes, and snippets.

@Eliav2

Eliav2/blog.md Secret

Created May 3, 2021 16:36
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Eliav2/3871a9dce0c035e5fd5c6a62ca6548e4 to your computer and use it in GitHub Desktop.
Save Eliav2/3871a9dce0c035e5fd5c6a62ca6548e4 to your computer and use it in GitHub Desktop.

How React hooks work - in depth

In simple cases, React Hooks will magically do exactly what you meant for, but in other cases, their behavior can feel inconsistent and unpredictable. the next article will try to deeply explain and demonstrate React hooks behavior.

The article consists of three main sections:

  • Definitions - this section summarizes important terms in React and web development which necessary for the rest of the article.
  • React Hooks - explains what type of hooks exists, what the difference between them, and how they behave.
  • Examples - examples that demonstrate everything explained in this article with an increasing difficulty rate.

Which of you that will finish reading the article to the end, and will really understand the latest example, will no longer be surprised by unexpected problems when using hooks in components with a complicated lifecycle.

The article is not for starters, and I will assume that you have some experience with React and React hooks.

code sandbox of all examples: https://codesandbox.io/s/github/Eliav2/how-react-hooks-work
webpage of sandbox(examples on full screen): https://d47vv.csb.app/
GitHub repo: https://github.com/Eliav2/how-react-hooks-work

Definitions

If you are not a React expert, It is strongly recommended to read the definitions section. You can start from the example section and then return to this section later if something is not clear.

the more important definitions here are: render, update, react hook and phase.

  • browser DOM - a tree of HTML elements. These elements make up everything the user sees in the browser, including this very page.
  • React - A library for manipulating React components.
  • React component - function(or class) that holds stateful logic managed by React lib, that component usually returns UI elements based on the stateful logic of the same component.
    React have class components, and functional components(FC).
  • React tree - a tree of React components(like the tree you can see in React devtools). this is not the same as the browser's DOM tree.
  • react renderer - ReactDOM in web(or react-native in mobile) - a library that knows how to manipulate React tree and 'render' it into the browser's DOM in the desired location(in react apps usually to root element). The renderer managing a Virtual DOM (VDOM) which is created and updated based on the given React tree.
  • render - this is the moment when React tree is created based on the current state.
    then the tree is passed to the renderer that will update the VDOM, and then will flush the changes into the browser's DOM.
  • update - when we say that a component 'updates', we are saying that the function component body re-executed (with possibly different props). it is possible that more the one update cycle will occur before a render. examples of the difference between update and render later.
  • react hook - A primitive that shares stateful logic with the parent Component. this is the reason hooks allowed only inside a body of a function component - hook is hooked to the parent component stateful logic. The hook and the parent component updates are triggers in the same phase, and the effects of the hook and the FC also fire in the same phase.
  • a component's phase - this is not an official term, I'm using this term in this tutorial to describe a different point of time in a React component. update: also React calls this phase.

Note - These definitions were summarized by me and may not be accurate, but they are sufficient to understand the rest of the article.

React Hooks

There 2 types of React hooks:

  • State hooks - like useState or useReducer. these hooks use and possibly manipulates the parent component stateful logic.
  • Effect hooks - one of useEffect or useLayoutEffect. these hooks receive a callback function and usually a dependency array. the callback function will be scheduled by React to fire on a later phase(see definition above). the exact phase is dependent on the effect that was chosen.
    Effects from the same type will be executed in the order of declaration.

Super Important Notes

  • Calling state hook from effect(like useEffect) will schedule another render.
  • Calling state hook from FC body will schedule another update call.

Render cycle

these are the phases of a render:

effects

  • update call - the moment FC body is executed. this is always the first phase of a render.

  • useLayoutEffect - it is triggered immediately after all the scheduled update calls executed, just before flushing changes to the browser's DOM and before useEffect.
    the docs say:

    Updates scheduled inside useLayoutEffect will be flushed synchronously before the browser has a chance to paint.

  • useEffect - it is triggered after all scheduled updates calls has been executed. this is always the last phase of a render.

after these phases, the 'render' step is completed and then ReactDOM will do the 'commit' step which basically just saying updating the browser's DOM based on the virtual DOM created by the render step. the 'commit' phase is not relevant for the purpose of this article.

cleanup effects

before each effect is fired a cleanup function is fired(if scheduled). the cleanup effects are:

  • useLayoutEffect cleanup
  • useEffect cleanup

Note - cleanup effect will never fire on the first render(because there is no prior effect to cleanup from).

Render cycle summary:

per render cycle: Each effect fires the most 1 times, excluding update call which fires at least once.

The effects are fired in this order(excluding the first render), and only if was scheduled:

  1. updateCall - may be called several times for a single render, and will occur one after another before any effect!
  2. useLayoutEffect cleanup
  3. useLayoutEffect
  4. useEffect cleanup
  5. useEffect

the AllPhases example demonstrates this very well.

Examples

important Note - each line of the code that will come next are part of the tutorial, even the comments. read them all to follow along. these examples are self-explanatory.

Basic

OK enough words. see the next example.

https://gist.github.com/00f3a6d57ac048358c3a81cca659a088

what order of logs would you expect when the component mounts? think for a second and replace the '?':

https://gist.github.com/58244e8a150ce02b448cbc7cdafb79d3

Reveal answer

well, the order is:

https://gist.github.com/a07b201fa3c486c8f158f47d9ebc77de

as we explained earlier, the function body fire first and then the effects.

code sandbox

BasicReverse

what will happen if we will replace the effects, does the order will change?

https://gist.github.com/ae32dc2a7e404ff88a4ec92861189c82

well, the order does change, and will be:

https://gist.github.com/4a02ade228649b71fd43f0db4da7b897

this is because effect hooks from the same type(here useEffect) are scheduled by React for the same phase and will be executed in the order of declaration, this is a common mistake to think that useEffect with an empty dependency array will fire on the mount and on a different phase from useEffect with no dependency array.

code sandbox

useLog

now let's create a log helper hook useLog that will let us keep track of the component phase for later examples:

https://gist.github.com/8a3aaac86d891afaacf6e84c9edaae5f

render.current and call.current will 'tick' at the same rate of the parent component because of hooks natures. This is simplified useLog, you will see different useLog hook in the UseLog.js file.

and usage:

https://gist.github.com/0df546f3ab307f5df755e2067715b229

code sandbox

unmount

if we will trigger unmount after mount the logs order will be:

https://gist.github.com/b77d18de7b4d4cb22d22f98412451e5e

when a component goes through unmounting step - the update phase does not happen, only the effect fire, in the order of declaration.

code sandbox

Effect vs LayoutEffect

useLayoutEffect is executed before useEffect:

https://gist.github.com/37ea7b31be049290bcce13ee31e1278e

code sandbox

AllPhases

This demonstrates all the different phases combined. after mount another dumy re-render is scheduled, we will use absolute timing for this example to see when each phase is executed:

https://gist.github.com/b81e863bafd43dfc2cd1a08473b15aac

this example deeply demonstrates all the different possible phases while a component renders. make sure you understand that before proceeding to the next examples.

code sandbox

UpdateCycle

when you set a state while in the update phase another update phase will be scheduled by React. let's try to force React to trigger 10 update calls before rendering.

https://gist.github.com/77f1dc9b33d90a9c03f18b3368bd69da

as we can see, we forced React to re-call the function body 10 times before performing the render. we can also notice that the render phase occurred 0.245ms after the last update call.

code sandbox

RenderCycle

Ok, so we saw what happens when we update the state while in the update phase, but what happens if we try to update the state when we are no longer in the update state? well, React will schedule an entire re-render cycle for the component. each render cycle will also include at least one update call.
let's force 5 render cycles:

https://gist.github.com/61d488ac5ebe39c3ddda11fc87d496cf

we can see that each render cycle comes with an update call.

code sandbox

CombinedCycle

now lets say we want 5 update calls for each render. let's force 3 renders:

https://gist.github.com/b2ffe85b9d76429033fabc0fbae32796

code sandbox

MultipleComponents

Let's combine the last 3 examples into the common parent.

https://gist.github.com/d0d47e135131e37cbb4d9c3d1db82548

now stop. think. what would you expect? does each component will go through her own update-render phases or maybe the update calls will occur one after another and then the effects one after another?

Reveal answer

the entire tree goes through the phase of the update, and only then the effects are fired.

https://gist.github.com/1d5b9ebd275b27df233209affc17fa14

code sandbox

phew! that was tough. if you read and understand everything to this point you can confidently say that you understand React hook's nature.

Component with complicated lifecycle

so why do we need to understand all of this? well, in simple cases you don't, but when dealing with a component with a complicated lifecycle you can sometimes get confused by the component's behavior. an example of such component will be react-xarrow which needs to trigger callback on different phases to get the right dimensions and activate animations callbacks on different phases, for that react-xarrows using react-use-call-onnext-render to schedule callback for later phases.

Recap

  • on each phase: An entire React Tree goes through each phase in a render cycle one after another, which means that if one component in the tree is in the useEffect phase for example, all the different components in the tree are currently also in the useEffect phase.
  • for a React Tree: on the same phase, each Component on React tree will fire each phase in the same order of the declaration of the react component in the React tree. for example:
    <>
      <Comp1/>
      <Comp2/>
    </>
    the useEffect if Comp1 will fire and only then the useEffect Comp2 will fire.
  • On the same React component: on the same phase, each effect from the same type will fire in the order of declaration.

That's it! you now understand what really going on when you asks React to update some state in some component.

If you liked this tutorial make sure to like it and share it! thank you for reading until the end!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment