When State Changes React Does Render Again

When does React re-render components?

React re-render explained

React is known for providing a fast user experience past only updating the parts of the UI that have changed.

When looking into React'south render functioning, there are a few terms and concepts that tin be hard to sympathize. Information technology wasn't 100% clear to me what a VDOM was or how React decides to re-return components for quite some time.

In the first part of this article, I'll explicate the most important concepts about rendering in React and how React decides to re-render a given component.

In the last section of this article, I'll show you lot what you can practice to optimize the render performance of your React application.

If, after reading this, you have open up questions or observe an mistake, feel gratuitous to leave a annotate or email me.

Table of Contents
  • Rendering in React

    • What is rendering?
    • What is the VDOM?
    • What does this mean for performance?
    • Want to see re-rendering in action?
  • When does React re-render?

    • Why doesn't my React component update when its props change?
  • Forcefulness a React component to rerender

    • Using React'south forceUpdate function
    • Strength an update in React hooks
  • How to optimize re-renders

    • Controlling when a component should update
    • Structure of your components
  • Conclusion

Rendering in React

What is rendering?

If we want to empathise how React renders and re-renders work, it'south a good thought to understand what happens behind the scenes of the library.

Rendering is a term that can be understood on different levels of abstraction. Depending on the context, it has a slightly dissimilar significant. In whatsoever case, ultimately, it describes the process of generating an paradigm.

To starting time off, we demand to understand what the DOM (Document Object Model) is:

"The W3C Certificate Object Model (DOM) is a platform and linguistic communication-neutral interface that allows programs and scripts to dynamically access and update the content, construction, and style of a document."

In evidently English, this means that the DOM represents what you see on your screen when yous open a website, expressed through the markup language HTML.

Browsers allow the JavaScript language to modify the DOM through an API: The globally available document represents that country of the HTML DOM and provides united states of america with functions to alter it.

You lot can modify the DOM with JavaScript through the DOM programming interface that contains functions similar document.write, Node.appendChild or Element.setAttribute.

What is the VDOM?

So we take the Virtual DOM (or VDOM) of React, another abstraction layer on peak of that. It consists of your React awarding'south elements.

State changes in your awarding will be applied to the VDOM beginning. If the new state of the VDOM requires a UI change, the ReactDOM library will efficiently practice this by trying to update merely what needs to be updated.

For case, if but the attribute of an element changes, React will but update the attribute of the HTML element past calling document.setAttribute (or something similar).

React VDOM explained

The red dots represent updates of the DOM tree.
Updating the VDOM doesn't necessarily trigger an update of the real DOM.

When the VDOM gets updated, React compares it to to a previous snapshot of the VDOM and and so only updates what has changed in the real DOM. If nothing inverse, the real DOM wouldn't be updated at all. This process of comparing the old VDOM with the new ane is called diffing .

Real DOM updates are slow because they cause an actual re-describe of the UI. React makes this more efficient past updating the smallest amount possible in the existent DOM.

Therefore we have to be enlightened of the divergence between native and virtual DOM updates.

Read more about how this works in React's documentation most reconciliation.

What does this mean for performance?

When we talk about renders in React, nosotros really talk about the execution of the render function, which doesn't e'er imply an update of the UI.

Let's encounter this in an instance:

                          const              App              =              (              )              =>              {              const              [message,              setMessage]              =              React.              useState              (              ''              )              ;              return              (                                                <                                >                                                                                          <                  Tile                                message                                  =                  {bulletin}                                />                                                                                          <                  Tile                                />                                                                                          </                                >                            )              ;              }              ;                      

In function components, the execution of the whole part is the equivalent of the render part in class components.

When the land changes in the parent component (in this case, App), the two Tile components volition re-render, even though the 2nd one doesn't even receive whatsoever props.

This translates to having the render function beingness called iii times, merely actual DOM modifications simply happen once in the Tile component that displays the bulletin:

React VDOM DOM diffing

The red dots again stand for renders.
In React, this means calling the render role. In the real DOM, this ways re-painting the UI.

The good news is that you don't have to worry besides much about the operation bottlenecks of UI re-draws. React already optimizes this for you lot.

The bad news is: All those red dots on the left-paw side hateful that the render function of these components has been executed.

The execution of these return functions has two drawbacks:

  1. React has to run its diffing algorithm on each of those components to cheque whether it should update the UI.
  2. All your code in these return functions or role components volition exist executed again.

The outset point is arguably not that important since React manages to summate the difference quite efficiently. The danger lies in the code that you wrote is beingness executed repeatedly on every React render.

In the case higher up, we take a pocket-size component tree. But imagine what happens if each node has more children, and these again might have child components. We'll run into how we tin can optimize this.

Want to run across re-rendering in action?

React DevTools lets you highlight renders under Components -> View Settings -> Highlight updates when components render. This will show you lot the virtual renders.

If you lot want to see native re-renders, you can do then in the Chrome DevTools, under the three-dot menu on the right -> More tools -> Rendering -> Paint flashing.

Now click through your application with kickoff the React re-renders highlighted, and then the native renders, and yous'll encounter how much React optimizes native rendering.

Example of Chrome's Paint Flashing pick in action.

When does React re-return?

Above we saw what causes a re-draw of our UI, only what is calling React'due south return role to begin with?

React schedules a return every time the state of a component changes.

Scheduling a render means that this doesn't happen immediately. React volition try to notice the all-time moment for this.

Changing the state means that React triggers an update when we phone call the setState function (in React hooks, you would utilize useState). This doesn't just mean the component'due south render function will be chosen, simply too that all its subsequent kid components will re-render, regardless of whether their props take changed or not.

If your application is poorly structured, you might be running a lot more than JavaScript than you expected because updating the parent node implies running the render role of all children.

In the last part of the article, we will come across a few tips that help you to prevent this kind of overhead.

Why doesn't my React component update when its props alter?

There are two mutual reasons why React might non update a component even though its props have inverse:

  1. The props weren't updated correctly via setState
  2. The reference to the prop stayed the aforementioned

Every bit we already saw before, React re-renders a component when you telephone call the setState role to change the state (or the provided function from the useState hook in function components).

Equally a result, the child components only update when the parent component's state changes with i of those functions.

Straight mutating the props object is non allowed since this won't trigger any changes, and React doesn't notice the changes.

                          this              .props.user.name              =              'Felix'              ;                      

Don't practice this!

Instead of changing the props like this, you need to alter the state in the parent component.

                          const              Parent              =              (              )              =>              {                              const                [user,                setUser]                =                React.                useState                (                {                name:                'Felix'                }                )                ;                            const              handleInput              =              (              e              )              =>              {              e.              preventDefault              (              )              ;                              setUser                (                {                                            ...user,                                            proper name:                e.target.value,                                            }                )                ;                            }              ;              render              (              <              >              <input onChange=              {handleInput}              value=              {user.name}              /              >              <Child user=              {user}              /              >              <              /              >              )              ;              }              ;              const              Kid              =              (                              {                user                }                            )              =>              (              <h1>              {user.name}              <              /h1>              )              ;                      

Information technology's important to change the state with the corresponding React functions. Yous tin can find the Codepen hither.

Note how I update the state using setUser, which is the function I go from React.useState. The equivalent to this in class components would be this.setState.

Force a React component to rerender

In the ii years that I've been working with React professionally, I've never come to a point where I needed to strength a re-render. I encourage you to read the commodity from the beginning if that's what you're hither for because usually there's a improve way of dealing with React components that aren't updating.

However, if you absolutely need to force an update, you tin can do then with the following methods:

Using React'southward forceUpdate function

This one is the most obvious one. In React class components, you can strength a re-render by calling this function:

Force an update in React hooks

In React hooks, the forceUpdate function isn't available. You can force an update without altering the components country with React.useState similar this:

                          const              [land,              updateState]              =              React.              useState              (              )              ;              const              forceUpdate              =              React.              useCallback              (              (              )              =>              updateState              (              {              }              )              ,              [              ]              )              ;                      

I got this one from StackOverflow. You'll probably never need it.

How to optimize re-renders

An example of inefficient re-renders is when a parent component controls the state of a child component. Think: When the country of a component changes, all children volition re-render.

I expanded the example I already used for explaining React.memo to have more nested children. Go ahead and try information technology out.

The numbers in yellow are counting the number of times the render part of each component has been executed:

Paints
0

Play around with the source code on codepen.

Even though we merely updated the land of the blue component, a lot more renders of other components have been triggered.

Decision-making when a component should update

React provides us with a few functions to prevent these unnecessary updates.

Let'due south take a look at them, later on this, I'll show you another, more effective way of improving render operation.

React.memo

The first one, which I already gave away before, is React.memo. I already wrote a more in-depth article on this, merely in summary, it'due south a function that prevents your React Hook components from rendering when the props don't change.

An example of this in action looks something like this:

                                          const                TileMemo                =                React.                memo                (                (                                  {                  children                  }                                )                =>                {                            let              updates              =              React.              useRef              (              0              )              ;              render              (                                                <div                className                                  =                  "black-tile"                                >                                                          Memo                                                                            <                  Updates                                updates                                  =                  {updates.current++                  }                                />                                                                      {children}                                                                                          </div                >                            )              ;              }              )              ;                      

At that place are a few more than things you need to know about this before using it in production. I recommend yous bank check out my article on React.memo after reading this one.

The equivalent for React classes is using React.PureComponent.

shouldComponentUpdate

This role is one of React's lifecycle functions and allows us to optimize rendering performance by telling React when to update a course component.

Its arguments are the next props and the next land that the component is nigh to return:

                          shouldComponentUpdate              (              nextProps,                nextState              )              {              // render true or false              }                      

This function is pretty easy to use: Returning true causes React to call the render role, returning simulated prevents this.

Fix the key attribute

In React, it is very common to do the following. Find out what's wrong with it:

                                                            <div                >                                                        {              events.              map              (              event              =>                                                <                  Event                                result                                  =                  {issue}                                />                            )              }                                                                            </div                >                                    

Here I forgot to set the key aspect. Almost linters will warn you about this, merely why is information technology and then important?

In some cases, React relies on the key aspect for identifying components and optimizing performance.

In the example in a higher place, if an event is being added to the first of the array, React will think that the first and all the subsequent elements take inverse and will trigger a re-return of those. We tin prevent this by calculation a key to the element:

                                                            <div                >                                                                      {              events.              map              (              event              =>                                                                    <                    Effect                                    outcome                                      =                    {event}                                    key                                      =                    {event.id}                                    />                                            )              }                                                                            </div                >                                    

Try to avoid using the index of the array every bit a key and use something that identifies the content.
Keys but take to be unique amid siblings.

Structure of your components

An even better way of improving re-renders is past restructuring your code a little flake.

Be conscientious where you place your logic. If you put everything in the root component of your application, all the React.memo functions in the earth won't help you lot to ready your operation issues.

If you place information technology closer to where the information is used, chances are you don't even need React.memo.

Check out the optimized version of the example and type in some text:

Paints
0

You lot run into that fifty-fifty though the land updates, the other components don't re-render at all.

The simply change I made was to move code that handles the land into a seperate component:

                          const              InputSelfHandling              =              (              )              =>              {              const              [text,              setText]              =              React.              useState              (              ''              )              ;              return              (                                                <input                value                                  =                  {text}                                placeholder                                  =                  "Write something"                                onChange                                  =                  {                  (                  e                  )                  =>                  setText                  (e.target.value)                  }                                />                            )              ;              }              ;                      

If y'all need to use the state in other parts of your application, you tin do so by using React Context or alternatives like MobX and Redux.

In this article, I explain component composition more than in detail and how it tin aid amend performance.

Conclusion

I promise I could give you lot a better agreement of how React's render mechanisms work and what yous tin do to go the most out of this. For this article, I had to do some additional research almost the topic to get a better agreement of how React'south render piece of work.

I intend to write more virtually frontend performance, so if yous want to go notified about the latest articles, follow me on Twitter and subscribe to my Email list.

If you came this far, you'll also want to check out my article near React.memo, which explains the API more in depth, some common pitfalls you could run across, and why you shouldn't always use React.memo. Thanks for reading.

bryantwrive1938.blogspot.com

Source: https://felixgerschau.com/react-rerender-components/

0 Response to "When State Changes React Does Render Again"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel