Thomas  Granger

Thomas Granger

1559696323

Under the hood of React’s hooks system

Looking at the implementation and getting to know it inside out

We’ve all heard about it. The new hook system of React 16.7 has made a lot of noise in the community. We’ve all tried it and tested it, and got really excited about it and its potential. When you think about hooks they’re kind of magical, somehow React manages your component without even exposing its instance (no use of this keyword). So how the heck does React does that?

Today I would like to dive into React’s implementation of hooks so we can understand it better. The problem with magical features is that it’s harder to debug a problem once it happens, because it’s backed by a complex stack trace. Thus, by having a deep knowledge regards React’s new hook system, we would be able to solve issues fairly quick once we encounter them, or even avoid them in the first place.

Before I begin I would just like to say that I’m not a developer/maintainer of React and that my words should be taken with a grain of salt. I did dive very deeply into the implementation of React’s hooks system, but by all means I can’t guarantee that this is how React actually works. With that said, I’ve backed my words with proofs and references from React’s source code, and tried to make my arguments as solid as possible.

A rough schematic representation of React’s hooks system

First of all, let’s go through the mechanism that ensures that hooks are called within React’s scope, because you’d probably know by now that hooks are meaningless if not called in the right context:

The dispatcher

The dispatcher is the shared object that contains the hook functions. It will be dynamically allocated or cleaned up based on the rendering phase of ReactDOM, and it will ensure that the user doesn’t access hooks outside a React component (see implementation).

The hooks are enabled/disabled by a flag called enableHooks right before we render the root component by simply switching to the right dispatcher; this means that technically we can enable/disable hooks at runtime. React 16.6.X also has the experimental feature implemented, but it’s actually disabled (see implementation).

When we’re done performing the rendering work, we nullify the dispatcher and thus preventing hooks from being accidentally used outside ReactDOM’s rendering cycle. This is a mechanism that will ensure that the user doesn’t do silly things (see implementation).

The dispatcher is resolved in each and every hook call using a function called resolveDispatcher(). Like I said earlier, outside the rendering cycle of React this should be meaningless, and React should print the warning message: “Hooks can only be called inside the body of a function component” (see implementation).

let currentDispatcher
const dispatcherWithoutHooks = { /* ... */ }
const dispatcherWithHooks = { /* ... */ }
function resolveDispatcher() {
if (currentDispatcher) return currentDispatcher
throw Error("Hooks can't be called")
}
function useXXX(...args) {
const dispatcher = resolveDispatcher()
return dispatcher.useXXX(...args)
}
function renderRoot() {
currentDispatcher = enableHooks ? dispatcherWithHooks : dispatcherWithoutHooks
performWork()
currentDispatcher = null
}

Dispatcher implementation in a nutshell.

Now that we got that simple encapsulation mechanism covered, I would like us to move to the core of this article — the hooks. Right of the bet I’d like to introduce you to a new concept:

The hooks queue

Behind the scenes, hooks are represented as nodes which are linked together in their calling order. They’re represented like so because hooks are not simply created and then left alone. They have a mechanism which allows them to be what they are. A hook has several properties which I would like you to bare in mind before diving into its implementation:

  • Its initial state is created in the initial render.
  • Its state can be updated on the fly.
  • React would remember the hook’s state in future renders.
  • React would provide you with the right state based on the calling order.
  • React would know which fiber does this hook belong to.

Accordingly, we need to rethink the way we view the a component’s state. So far we have thought about it as if it’s a plain object:

{
foo: 'foo',
bar: 'bar',
baz: 'baz',
}

React state — the old way.

But when dealing with hooks it should be viewed as a queue, where each node represents a single model of the state:

{
memoizedState: 'foo',
next: {
memoizedState: 'bar',
next: {
memoizedState: 'bar',
next: null
}
}
}

React state — the new way.

The schema of a single hook node can be viewed in the implementation. You’ll see that the hook has some additional properties, but the key for understanding how hooks work lies within memoizedState and next. The rest of the properties are used specifically by the useReducer() hook to cache dispatched actions and base states so the reduction process can be repeated as a fallback in various cases:

  • Its initial state is created in the initial render.
  • Its state can be updated on the fly.
  • React would remember the hook’s state in future renders.
  • React would provide you with the right state based on the calling order.
  • React would know which fiber does this hook belong to.

Unfortunately I haven’t managed to get a good grasp around the reducer hook because I didn’t manage to reproduce almost any of its edge cases, so I wouldn’t feel comfortable to elaborate. I will only say that the reducer implementation is so inconsistent that even one of the comments in the implementation itself states that “(it’s) not sure if these are the desired semantics”; so how am I supposed to be sure?!

So back to hooks, before each and every function Component invocation, a function named [prepareHooks()](https://github.com/facebook/react/tree/5f06576f51ece88d846d01abd2ddd575827c6127/react-reconciler/src/ReactFiberHooks.js:123 "prepareHooks()") is gonna be called, where the current fiber and its first hook node in the hooks queue are gonna be stored in global variables. This way, any time we call a hook function (useXXX()) it would know in which context to run.

let currentlyRenderingFiber
let workInProgressQueue
let currentHook
// Source: https://github.com/facebook/react/tree/5f06576f51ece88d846d01abd2ddd575827c6127/react-reconciler/src/ReactFiberHooks.js:123
function prepareHooks(recentFiber) {
currentlyRenderingFiber = workInProgressFiber
currentHook = recentFiber.memoizedState
}
// Source: https://github.com/facebook/react/tree/5f06576f51ece88d846d01abd2ddd575827c6127/react-reconciler/src/ReactFiberHooks.js:148
function finishHooks() {
currentlyRenderingFiber.memoizedState = workInProgressHook
currentlyRenderingFiber = null
workInProgressHook = null
currentHook = null
}
// Source: https://github.com/facebook/react/tree/5f06576f51ece88d846d01abd2ddd575827c6127/react-reconciler/src/ReactFiberHooks.js:115
function resolveCurrentlyRenderingFiber() {
if (currentlyRenderingFiber) return currentlyRenderingFiber
throw Error("Hooks can't be called")
}
// Source: https://github.com/facebook/react/tree/5f06576f51ece88d846d01abd2ddd575827c6127/react-reconciler/src/ReactFiberHooks.js:267
function createWorkInProgressHook() {
workInProgressHook = currentHook ? cloneHook(currentHook) : createNewHook()
currentHook = currentHook.next
workInProgressHook
}
function useXXX() {
const fiber = resolveCurrentlyRenderingFiber()
const hook = createWorkInProgressHook()
// ...
}
function updateFunctionComponent(recentFiber, workInProgressFiber, Component, props) {
prepareHooks(recentFiber, workInProgressFiber)
Component(props)
finishHooks()
}

*Hooks queue implementation in a nutshell.*

Once an update has finished, a function named [finishHooks()](https://github.com/facebook/react/tree/5f06576f51ece88d846d01abd2ddd575827c6127/react-reconciler/src/ReactFiberHooks.js:148 "finishHooks()") will be called, where a reference for the first node in the hooks queue will be stored on the rendered fiber in the memoizedState property. This means that the hooks queue and their state can be addressed externally:

const ChildComponent = () => {
useState('foo')
useState('bar')
useState('baz')
return null
}
const ParentComponent = () => {
const childFiberRef = useRef()
useEffect(() => {
let hookNode = childFiberRef.current.memoizedState
assert(hookNode.memoizedState, 'foo')
hookNode = hooksNode.next
assert(hookNode.memoizedState, 'bar')
hookNode = hooksNode.next
assert(hookNode.memoizedState, 'baz')
})
return (
<ChildComponent ref={childFiberRef} />
)
}

An external read of a component’s memoized state.

Let’s get more specific and talk about individual hooks, starting with the most common of all — the state hook:

State hooks

You would be surprised to know, but behind the scenes the useState hook uses useReducer and it simply provides it with a pre-defined reducer handler (see implementation). This means that the results returned by useState are actually a reducer state, and an action dispatcher. I would like you to take a look at the reducer handler that the state hook uses:

function basicStateReducer(state, action) {
return typeof action === 'function' ? action(state) : action;
}

State hook reducer, aka basic state reducer.

So as expected, we can provide the action dispatcher with the new state directly; but would you look at that?! We can also provide the dispatcher with *an action function that will receive the old state and return the new one. *T̶̶̶h̶̶̶i̶̶̶s̶̶̶ ̶̶̶i̶̶̶s̶̶̶n̶̶̶’̶̶̶t̶̶̶ ̶̶̶d̶̶̶o̶̶̶c̶̶̶u̶̶̶m̶̶̶e̶̶̶n̶̶̶t̶̶̶e̶̶̶d̶̶̶ ̶̶̶a̶̶̶n̶̶̶y̶̶̶w̶̶̶h̶̶̶e̶̶̶r̶̶̶e̶̶̶ ̶̶̶i̶̶̶n̶̶̶ ̶̶̶t̶̶̶h̶̶̶e̶̶̶ ̶̶̶o̶̶̶f̶̶̶f̶̶̶i̶̶̶c̶̶̶i̶̶̶a̶̶̶l̶̶̶ ̶̶̶R̶̶̶e̶̶̶a̶̶̶c̶̶̶t̶̶̶ ̶̶̶d̶̶̶o̶̶̶c̶̶̶u̶̶̶m̶̶̶e̶̶̶n̶̶̶t̶̶̶a̶̶̶t̶̶̶i̶̶̶o̶̶̶n̶̶̶ ̶̶̶(̶̶̶a̶̶̶s̶̶̶ ̶̶̶f̶̶̶o̶̶̶r̶̶̶ ̶̶̶t̶̶̶h̶̶̶e̶̶̶ ̶̶̶t̶̶̶i̶̶̶m̶̶̶e̶̶̶ ̶̶̶t̶̶̶h̶̶̶i̶̶̶s̶̶̶ ̶̶̶a̶̶̶r̶̶̶t̶̶̶i̶̶̶c̶̶̶l̶̶̶e̶̶̶ ̶̶̶w̶̶̶a̶̶̶s̶̶̶ ̶̶̶w̶̶̶r̶̶̶i̶̶̶t̶̶̶t̶̶̶e̶̶̶n̶̶̶)̶̶̶ ̶̶̶a̶̶̶n̶̶̶d̶̶̶ ̶̶̶ ̶t̶h̶a̶t̶’̶s̶ ̶a̶ ̶p̶i̶t̶y̶ ̶b̶e̶c̶a̶u̶s̶e̶ ̶i̶t̶’̶s̶ ̶e̶x̶t̶r̶e̶m̶e̶l̶y̶ ̶u̶s̶e̶f̶u̶l̶!̶ This means that when you send the state setter down the component tree you can run mutations against the current state of the parent component, without passing it as a different prop. For example:

const ParentComponent = () => {
const [name, setName] = useState()
return (
<ChildComponent toUpperCase={setName} />
)
}
const ChildComponent = (props) => {
useEffect(() => {
props.toUpperCase((state) => state.toUpperCase())
}, [true])
return null
}

Returning a new state relatively to the old one.

Lastly, effect hooks — which made a major impact on a component’s life cycle and how it works:

Effect hooks

Effect hooks behave slightly differently and has an additional layer of logic that I would like to explain. Again, there are things I would like you to bare in mind regards the properties of the effect hooks before I dive into the implementation:

  • Its initial state is created in the initial render.
  • Its state can be updated on the fly.
  • React would remember the hook’s state in future renders.
  • React would provide you with the right state based on the calling order.
  • React would know which fiber does this hook belong to.

Before I begin I would just like to say that I’m not a developer/maintainer of React and that my words should be taken with a grain of salt. I did dive very deeply into the implementation of React’s hooks system, but by all means I can’t guarantee that this is how React actually works. With that said, I’ve backed my words with proofs and references from React’s source code, and tried to make my arguments as solid as possible.
Accordingly, there should be another an additional queue that should hold these effects and should be addressed after painting. Generally speaking, a fiber holds a queue which contains effect nodes. Each effect is of a different type and should be addressed at its appropriate phase:

  • Its initial state is created in the initial render.
  • Its state can be updated on the fly.
  • React would remember the hook’s state in future renders.
  • React would provide you with the right state based on the calling order.
  • React would know which fiber does this hook belong to.

When it comes to the hook effects, they should be stored on the fiber in a property called updateQueue, and each effect node should have the following schema (see implementation):

  • Its initial state is created in the initial render.
  • Its state can be updated on the fly.
  • React would remember the hook’s state in future renders.
  • React would provide you with the right state based on the calling order.
  • React would know which fiber does this hook belong to.

Besides the tag property, the other properties are pretty straight forward and easy to understand. If you’ve studied hooks well, you’d know that React provides you with a couple of special effect hooks: useMutationEffect() and useLayoutEffect(). These two effects internally use useEffect(), which essentially mean that they create an effect node, but they do so using a different tag value.

The tag is composed out of a combination of binary values (see implementation):

const NoEffect = /* */ 0b00000000;
const UnmountSnapshot = /* */ 0b00000010;
const UnmountMutation = /* */ 0b00000100;
const MountMutation = /* */ 0b00001000;
const UnmountLayout = /* */ 0b00010000;
const MountLayout = /* */ 0b00100000;
const MountPassive = /* */ 0b01000000;
const UnmountPassive = /* */ 0b10000000;

Supported hook effect types by React.

The most common use cases for these binary values would be using a pipeline (|) and add the bits as is to a single value. Then we can check whether a tag implements a certain behavior or not using an ampersand (&). If the result is non-zero, it means that the tag implements the specified behavior.

const effectTag = MountPassive | UnmountPassive
assert(effectTag, 0b11000000)
assert(effectTag & MountPassive, 0b10000000)

An example which shows how to use React’s binary design pattern.

Here are the supported hook effect types by React along with their tags (see implementation):

  • Its initial state is created in the initial render.
  • Its state can be updated on the fly.
  • React would remember the hook’s state in future renders.
  • React would provide you with the right state based on the calling order.
  • React would know which fiber does this hook belong to.

And here’s how React checks for behavior implementation (see implementation):

if ((effect.tag & unmountTag) !== NoHookEffect) {
// Unmount
}
if ((effect.tag & mountTag) !== NoHookEffect) {
// Mount
}

A real snapshot from React’s implementation.

So, based on what we’ve just learned regards effect hooks, we can actually inject an effect to a certain fiber externally:

function injectEffect(fiber) {
const lastEffect = fiber.updateQueue.lastEffect
const destroyEffect = () => {
console.log('on destroy')
}
const createEffect = () => {
console.log('on create')
return destroy
}
const injectedEffect = {
tag: 0b11000000,
next: lastEffect.next,
create: createEffect,
destroy: destroyEffect,
inputs: [createEffect],
}
lastEffect.next = injectedEffect
}
const ParentComponent = (
<ChildComponent ref={injectEffect} />
)

Example of effects injection.

So that was it! What was your biggest takeout from this article? How are you gonna use this new knowledge in your React apps? Would love to see interesting comments!

#reactjs #javascript #web-development

What is GEEK

Buddha Community

Under the hood of React’s hooks system
Autumn  Blick

Autumn Blick

1598839687

How native is React Native? | React Native vs Native App Development

If you are undertaking a mobile app development for your start-up or enterprise, you are likely wondering whether to use React Native. As a popular development framework, React Native helps you to develop near-native mobile apps. However, you are probably also wondering how close you can get to a native app by using React Native. How native is React Native?

In the article, we discuss the similarities between native mobile development and development using React Native. We also touch upon where they differ and how to bridge the gaps. Read on.

A brief introduction to React Native

Let’s briefly set the context first. We will briefly touch upon what React Native is and how it differs from earlier hybrid frameworks.

React Native is a popular JavaScript framework that Facebook has created. You can use this open-source framework to code natively rendering Android and iOS mobile apps. You can use it to develop web apps too.

Facebook has developed React Native based on React, its JavaScript library. The first release of React Native came in March 2015. At the time of writing this article, the latest stable release of React Native is 0.62.0, and it was released in March 2020.

Although relatively new, React Native has acquired a high degree of popularity. The “Stack Overflow Developer Survey 2019” report identifies it as the 8th most loved framework. Facebook, Walmart, and Bloomberg are some of the top companies that use React Native.

The popularity of React Native comes from its advantages. Some of its advantages are as follows:

  • Performance: It delivers optimal performance.
  • Cross-platform development: You can develop both Android and iOS apps with it. The reuse of code expedites development and reduces costs.
  • UI design: React Native enables you to design simple and responsive UI for your mobile app.
  • 3rd party plugins: This framework supports 3rd party plugins.
  • Developer community: A vibrant community of developers support React Native.

Why React Native is fundamentally different from earlier hybrid frameworks

Are you wondering whether React Native is just another of those hybrid frameworks like Ionic or Cordova? It’s not! React Native is fundamentally different from these earlier hybrid frameworks.

React Native is very close to native. Consider the following aspects as described on the React Native website:

  • Access to many native platforms features: The primitives of React Native render to native platform UI. This means that your React Native app will use many native platform APIs as native apps would do.
  • Near-native user experience: React Native provides several native components, and these are platform agnostic.
  • The ease of accessing native APIs: React Native uses a declarative UI paradigm. This enables React Native to interact easily with native platform APIs since React Native wraps existing native code.

Due to these factors, React Native offers many more advantages compared to those earlier hybrid frameworks. We now review them.

#android app #frontend #ios app #mobile app development #benefits of react native #is react native good for mobile app development #native vs #pros and cons of react native #react mobile development #react native development #react native experience #react native framework #react native ios vs android #react native pros and cons #react native vs android #react native vs native #react native vs native performance #react vs native #why react native #why use react native

What are hooks in React JS? - INFO AT ONE

In this article, you will learn what are hooks in React JS? and when to use react hooks? React JS is developed by Facebook in the year 2013. There are many students and the new developers who have confusion between react and hooks in react. Well, it is not different, react is a programming language and hooks is a function which is used in react programming language.
Read More:- https://infoatone.com/what-are-hooks-in-react-js/

#react #hooks in react #react hooks example #react js projects for beginners #what are hooks in react js? #when to use react hooks

Hayden Slater

1599277908

Validating React Forms With React-Hook-Form

Validating inputs is very often required. For example, when you want to make sure two passwords inputs are the same, an email input should in fact be an email or that the input is not too long. This is can be easily done using React Hook From. In this article, I will show you how.

Required Fields

The most simple, yet very common, validation is to make sure that an input component contains input from the user. React Hook Form basic concept is to register input tags to the form by passing register() to the tag’s ref attribute. As we can see here:

#react-native #react #react-hook-form #react-hook

The Ugly Side of React Hooks

In this post, I will share my own point of view about React Hooks, and as the title of this post implies, I am not a big fan.

Let’s break down the motivation for ditching classes in favor of hooks, as described in the official React’s docs.

Motivation #1: Classes are confusing

we’ve found that classes can be a large barrier to learning React. You have to understand how "this"_ works in JavaScript, which is very different from how it works in most languages. You have to remember to bind the event handlers. Without unstable syntax proposals, the code is very verbose […] The distinction between function and class components in React and when to use each one leads to disagreements even between experienced React developers._

Ok, I can agree that

thiscould be a bit confusing when you are just starting your way in Javascript, but arrow functions solve the confusion, and calling a_stage 3_feature that is already being supported out of the box by Typescript, an “unstable syntax proposal”, is just pure demagoguery. React team is referring to theclass fieldsyntax, a syntax that is already being vastly used and will probably soon be officially supported

class Foo extends React.Component {
  onPress = () => {
    console.log(this.props.someProp);
  }

  render() {
    return <Button onPress={this.onPress} />
  }
}

As you can see, by using a class field arrow function, you don’t need to bind anything in the constructor, and

this will always point to the correct context.

And if classes are confusing, what can we say about the new hooked functions? A hooked function is not a regular function, because it has state, it has a weird looking

this(aka_useRef_), and it can have multiple instances. But it is definitely not a class, it is something in between, and from now on I will refer to it as aFunclass. So, are those Funclasses going to be easier for human and machines? I am not sure about machines, but I really don’t think that Funclasses are conceptually easier to understand than classes. Classes are a well known and thought out concept, and every developer is familiar with the concept ofthis, even if in javascript it’s a bit different. Funclasses on the other hand, are a new concept, and a pretty weird one. They feel much more magical, and they rely too much on conventions instead of a strict syntax. You have to follow somestrict and weird rules, you need to be careful of where you put your code, and there are many pitfalls. Telling me to avoid putting a hook inside anifstatement, because the internal mechanism of hooks is based on call order, is just insane! I would expect something like this from a half baked POC library, not from a well known library like React. Be also prepared for some awful naming like useRef (a fancy name forthis),useEffect ,useMemo,useImperativeHandle(say whatt??) and more.

The syntax of classes was specifically invented in order to deal with the concept of multiple instances and the concept of an instance scope (the exact purpose of

this ). Funclasses are just a weird way of achieving the same goal, using the wrong puzzle pieces. Many people are confusing Funclasses with functional programming, but Funclasses are actually just classes in disguise. A class is a concept, not a syntax.

Oh, and about the last note:

The distinction between function and class components in React and when to use each one leads to disagreements even between experienced React developers

Until now, the distinction was pretty clear- if you needed a state or lifecycle methods, you used a class, otherwise it doesn’t really matter if you used a function or class. Personally, I liked the idea that when I stumbled upon a function component, I could immediately know that this is a “dumb component” without a state. Sadly, with the introduction of Funclasses, this is not the situation anymore.

#react #react-hooks #javascript #reactjs #react-native #react-hook #rethinking-programming #hackernoon-top-story

Juana  O'Keefe

Juana O'Keefe

1603127640

Hooks, Hooks, Hooks!

Prior to 2018, React, an already powerful and widely-used javascript library for building user interfaces, had 3 cumbersome issues:

  1. Reusing logic: in order to to create dynamic interfaces where state is manipulated, logic was constantly being copied for seemingly simple tasks like updating the state from a form field. This often would lead to complicated and bloated data structures.
  2. Giant components: logic often times gets split amongst various lifecycle. methods in order to keep your application working.
  3. Confusing classes: invariably with reused logic and oversized components, our classes themselves can become confusing for both user and the machine.

As Dan Abramov of the React Dev team describes it, these are really three separate issues, but rather systems of the same problem: before 2018, _React did not provide a stateful primitive that is simpler than incorporating a class component and its associated logic. _At one point, React used mixins to pseudo-resolve this issue, but that ultimately created more problems that it solved.

How did the React team resolve this seemingly singular, but hugely impactful inconvenience? Hooks to the rescue.

Image for post

#software-engineering #react-conf-2018 #hooks #react #react-conference #react native