What’s behind the legendary React Hooks? From time to time, I wonder.

In Part 2, useEffect and all of its usages were examined in detail. In this Part 3, we’d like to continue and dive in useState.

function Component() {
const [value, setValue] = useState(initialValue);
...
return (<div />)
}

Initialize the state with an initial value. When needed, notify the Element by calling setState with the new value.

The value provided can be used directly in the Component definition. And it can be further sent into the children components.

function Component() {
const [value, setValue] = useState(initialValue)…


What’s behind the legendary Hooks in React? From time to time, I wonder.

In Part 1, we went through Element to explain the general Hooks concept. In this Part 2, we’d like to take a dive into the useEffect and see how it supports the callback, teardown, and dependencies.

In order to hook into element, the callback needs to be registered.

function Component() {
useEffect(() => { window.title = "ABC" })
}

The effects are always on by default, and are invoked upon each update.

useEffect(() => {
...
return () => {
...
}
})

Normally there’s no return


What’s behind the legendary Hooks in React? From time to time, I wonder.

Captain Hooks. Find me if you can.

Given a Component, pass it on to a helper function component where it generates a new Element class used by the UI system. Inside this class the additional Hook properties, such as states and effects, are allocated and ready for Hooks.

/* Implementation */
function component(renderer) {
class Element {
constructor() {
this.renderer = renderer
this.states = {}
this.effects = {}
this.queued = false
}
...
}
return Element
}
/* Usage */
const Component = () => <div />
component(Component) // can be transparent to us


Photo by Scott Graham on Unsplash

Imaging for a second you can get any help you want, what type of help do you need for your project?

Project

Of course, we need a project. Though obvious, decent amount of details need to be presented before meaningful architect, or right architect so to speak. You have limited market share to capture, you have limited budget to spend, you have limited resources to work for you. Moreover you get limited expansion power, for instance, your imagination (or time, or business requirement) might dry out sooner than you think.

In short, you need some historical context to sink in before…


Is this level of trouble worth it in the end?

Like any tech-savvy person who would chase the latest computer spec, I’m very much into understanding what’s really going on with a new language, especially when the new language starts to show its potential in practical fields.

Function

The learning isn’t that difficult, at least not the beginning. I’ve been practicing the functional programming, comfortable of functions as a first class citizens, and strongly feeling that function probably is what the programming is about, not the implementation.

>>> length (takeWhile (<1000) (scanl1 (+) (map sqrt [1..]))) + 1

With recursive feature…


Understand the useState hook’s workflow from the stripped-down version of the official React source code.

Photo by Ferenc Almasi on Unsplash
const Title = () => {
const [state, setState] = useState(initialState)
}

I read some implementations of useState from preact and brahmos repositories. And I thought I understood the behavior of useState until I finally read the official version under ReactFiberHooks.old.js. Of course it’s not an easy read, anyway I bite the bullet with a lot of help from other people who read the source code :)

In order to understand the official source code, let me strip it down a bit so that we can follow the key workflow without going through hundreds of lines in many repositories.

Learning from the source code

The…


Thanks for the article.

If I understand right, you are basically triggering second pass in all solutions. Because the first "render" is done by server, therefore whatever the states set are settled.

When you display anything from the server, you get what's been set. And now if you want to change that fact, you ask a hook `useEffect` to run once after the first "render" on client.

However the root problem I believe is that if we need to set a value, we can

a) like `next.js`, provide it from server

b) just wire it with a state

```

const [value] = useState(() => { expensive one })

```

IMHO the reason i don't suggest your approach is that second render path a) smells not right b) beats the purpose of ssr.


What’s behind the legendary React Hooks? From time to time, I wonder.

In Part 7 we talked about a single state management system of our own. In this Part 8, we’d like to put it in use and see how it can be applied to real problems, especially when we encounter the four-body (or N body) problem.

Typically a site starts with App that has a Header and multiple Routes.


What’s behind the legendary React Hooks? From time to time, I wonder.

In Part 6 we examined a relative complex hook useContext and see how state can be used to drive element update. In this Part 7, we’d like to create our own state management based on this understanding.

We know by now calling setState triggers an update of Component where this useState is registered at.

Let us start with one value and setValue.

The most common case is to use setValue in an event handler, such as click.

const Single = () => {
const [value, setValue] = useState(1)
const onClick = () => { setValue(2) }
}

Or you can…

Fang Jin

Front-end Engineer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store