A Beginner's Guide to React Fiber

Before we understand how & what fiber is, let us understand what exactly happens when you want to render something on the Browser using react

It includes 2 main components

  • Reconciler
  • Renderer

Reconciler

All the changes that needs to be applied to the current tree of React Elements to reflect the updated state on the browser is determined by the reconciler during reconciliation

Note : The browser doesn’t reflect the changes made during reconciliation

Renderer

Once your tree is ready you need to apply these changes on the browser, renderer does that for you. Renderer updates your rendered app by taking care of all the platform specific calls.

Example: react-dom which updates the DOM. react-native is another popular renderer. These are just few of the many pluggable renderers available.

P.S – You can also create your own custom renderer, isn’t that great!!

When it comes to Fiber, its actually a re-implementaion of the React’s core reconciliation algorithm.

But why to re-write something from scratch?

In order to understand this we need to know how React’s old reconciliation algorithm worked. Let me explain you in a nutshell.

You only have one main thread in javascript that does your UI updation, state change, network computation & responding to user’s action.

  • At any point in time React has 2 tree’s (VDOM tree) in memory, the current tree which is already rendered and the updated tree with all the latest changes.
  • The Stack reconciler finds the difference between 2 tree’s synchronously in a single pass
  • This prevents the main thread from doing potential urgent work until the recursive process has finished.
  • If user happens to type in a text input during this phase, your app becomes unresponsive as main thread is busy. A similar kind of thing happens when an animation needs to happen and your main thread is busy, that’s when you experience Jank.

This had to be solved.

This is where fiber comes into picture

So What is Fiber?

Fiber is a new data structure which represents a unit of work

In simple terms it is a javascript object that maintains a one to one relationship with the react instances

Rendering the Fiber Tree

The first fiber node which react creates is the host root which represents the container dom node ( the dom element which you pass to ReactDOM.render() )

Fiber object has specific properties which allows it to keep track of information and relationship between fiber nodes

FiberNode{  
   stateNode,
   child,
   sibling,
   return,
   type,
   alternate,
   key,
   updateQueue,
   memoizedState,
   pendingProps,
   memoizedProps,
   tag,
   effectTag,
   nextEffect,

}

stateNode keeps reference to the component instance fiber belongs to

child, sibling & return represents the child, siblings and the parent node with respect to the current fiber node

type determines if its a class or function or DOM element

alternate holds the reference between the nodes in current tree and work-in-progress tree

key identifies all the changed, added, or removed elements

updateQueue queues all the state & DOM updates or any other effect

memoizedState holds the reference to the state of the previous render

memoizedProps holds the reference to the props supplied to the previous render

pendingProps represents the new props passed for the current update

tag denotes the type of Fiber example: Class component, Function component, Host portal.

effectTag holds the information about the side-effect which needs to be applied

nextEffect points to the next node in the effects list which has an update

React starts creating a fiber tree upon initial render known as current fiber tree.

Whenever there is an update, React starts building the work in progress(WIP) fiber tree

Why WIP?

So that there are no partial changes in the DOM. Once all the work is calculated by React then all the DOM updates are applied together which is what makes React Fiber so performant and smooth.

In stack Reconciler as soon as the instance was updated, the DOM used to be updated without having any information about the subsequent changes which was making the UI inconsistent.

How does Fiber avoid UI inconsistency?

By simply splitting work in Phases

  1. Render / Reconciliation phase
  2. Commit phase

Phase 1 can be paused and resumed whereas Phase 2 must be completed in one go

In phase 1 react starts building the WIP tree, which goes about something like this

  • setState() method is called to update a component’s state
  • React knows it has to now schedule the work using requestIdleCallback() which lets the main thread know that it has to pick up the work once it has some free(Idle) time
  • React now starts creating the WIP Fiber tree by cloning the elements from the current Fiber tree and goes through each node to determine if it has to be changed
  • If a particular node has an update, it is added to another list called as effects list which is a linear linked list of all the changes that needs to be made
  • Once entire WIP tree is traversed and all the updated nodes are tagged, phase 1 is completed

In Phase 2 (commit phase), all the updates for the nodes in the effect list are performed and reflected on the DOM.The main thread applies all these changes in a single go

But how does it solve my jank problem??

One of the most differentiating feature in React Fiber is Prioritization. Fiber reconciler can prioritize different tasks which needs to be done.

So if your application is doing some data fetching while the user is typing something in the textbox, updating the UI to reflect users text would be given higher priority as compared to fetching the data.

Takeaway tip

Always use the updater function while working with React Fiber

setState() with a function as argument instead of object is an updater function

this.setState((state, props) => {
  return {
    ...
  }
})

Using updater function always guarantees that the state and props will always be up-to-date

Conclusion

Fiber in nutshell allows React to better utilize the main thread by pausing/ resuming/ prioritising/ cancelling updates to provide a seamless user experience.

#reactjs #web-development #javascript

A Beginner's Guide to React Fiber
110.25 GEEK