How to rerender component react

How to rerender component react

Re-rendering Components in ReactJS

As we know React JS is an open source JavaScript library that is used for building user interfaces specifically for single-page applications. It is also known for providing fast user experience by only updating the parts of the UI that have changed. Rendering components is not in user hands, it is a part of React Component Lifecycle and is called by React at various app stages, generally when the React Component is first instantiated. A second or subsequent render to update the state is called as re-rendering. React components automatically re-render whenever there is a change in their state or props.

A simple update of the state, from anywhere in the code, causes all the User Interface (UI) elements to be re-rendered automatically. However, there may be cases where the render() method depends on some other data. Re-render can be caused due to any of the three reasons listed:

Unnecessary re-renders affect the app performance and cause loss of users’ battery which surely no user would want. Let’s see in detail why components get re-rendered and how to prevent unwanted re-rendering to optimize app components.

Why do components get re-rendered?

Let’s have a deeper look at the three causes of re-rendering mentioned before.

React schedules a render every time state changes (scheduling a render doesn’t mean this happens immediately, this might take time and be done at the best moment). Changing a state means React triggers an update when we call the useState function (useState is a Hook that allows you to have state variables in functional components).

Example: Creating a simple Counter React Project will help to understand the concept of re-rendering components.

Prerequisite: Download VS Code and Node packages.
Step 1: Create a new React project named counter-app by running the below given command.

Step 2: Once the installation is done, you can open the project folder as shown below.

Step 3: After creating the React JS application, install the required module by running the below given command.

Step 4: Open VS Code go to the explorer in VS Code (press crtl+shift+E). Next, go to src folder->New file as shown. And name it Child.js (this is the child component).

How to rerender component react. Смотреть фото How to rerender component react. Смотреть картинку How to rerender component react. Картинка про How to rerender component react. Фото How to rerender component react

Making of child component

Project Structure: It will look like the following.

How to rerender component react. Смотреть фото How to rerender component react. Смотреть картинку How to rerender component react. Картинка про How to rerender component react. Фото How to rerender component react

Step 5: Edit the code in the App.js file as shown.

App.js File will have the following:

The code gives a message each time the component’s render function is called. Each time the count button is clicked state change is triggered.

When does React re-render components?

How to rerender component react. Смотреть фото How to rerender component react. Смотреть картинку How to rerender component react. Картинка про How to rerender component react. Фото How to rerender component react

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

When looking into React’s render performance, there are a few terms and concepts that can be hard to understand. It wasn’t 100% clear to me what a VDOM was or how React decides to re-render components for quite some time.

In the first part of this article, I’ll explain 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 what you can do to optimize the render performance of your React application.

If, after reading this, you have open questions or find an error, feel free to leave a comment or email me.

Table of Contents

Rendering in React

What is rendering?

If we want to understand how React renders and re-renders work, it’s a good idea 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 different meaning. In any case, ultimately, it describes the process of generating an image.

To start off, we need to understand what the DOM (Document Object Model) is:

«The W3C Document Object Model (DOM) is a platform and language-neutral interface that allows programs and scripts to dynamically access and update the content, structure, and style of a document.»

In plain English, this means that the DOM represents what you see on your screen when you 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 state of the HTML DOM and provides us with functions to modify it.

What is the VDOM?

Then we have the Virtual DOM (or VDOM) of React, another abstraction layer on top of that. It consists of your React application’s elements.

State changes in your application will be applied to the VDOM first. If the new state of the VDOM requires a UI change, the ReactDOM library will efficiently do this by trying to update only what needs to be updated.

For example, if only the attribute of an element changes, React will only update the attribute of the HTML element by calling document.setAttribute (or something similar).

How to rerender component react. Смотреть фото How to rerender component react. Смотреть картинку How to rerender component react. Картинка про How to rerender component react. Фото How to rerender component react

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

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

Therefore we have to be aware of the difference between native and virtual DOM updates.

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

What does this mean for performance?

When we talk about renders in React, we really talk about the execution of the render function, which doesn’t always imply an update of the UI.

Let’s see this in an example:

When the state changes in the parent component (in this case, App ), the two Tile components will re-render, even though the second one doesn’t even receive any props.

This translates to having the render function being called three times, but actual DOM modifications only happen once in the Tile component that displays the message:

How to rerender component react. Смотреть фото How to rerender component react. Смотреть картинку How to rerender component react. Картинка про How to rerender component react. Фото How to rerender component react

The good news is that you don’t have to worry too much about the performance bottlenecks of UI re-draws. React already optimizes this for you.

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

The execution of these render functions has two drawbacks:

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

In the example above, we have a small component tree. But imagine what happens if each node has more children, and these again might have child components. We’ll see how we can optimize this.

Want to see re-rendering in action?

Now click through your application with first the React re-renders highlighted, and then the native renders, and you’ll see how much React optimizes native rendering.

When does React re-render?

Above we saw what causes a re-draw of our UI, but what is calling React’s render function to begin with?

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

Scheduling a render means that this doesn’t happen immediately. React will try to find the best moment for this.

Changing the state means that React triggers an update when we call the setState function (in React hooks, you would use useState ). This doesn’t only mean the component’s render function will be called, but also that all its subsequent child components will re-render, regardless of whether their props have changed or not.

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

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

Why doesn’t my React component update when its props change?

There are two common reasons why React might not update a component even though its props have changed:

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

As a result, the child components only update when the parent component’s state changes with one of those functions.

Directly mutating the props object is not allowed since this won’t trigger any changes, and React doesn’t notice the changes.

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

It’s important to change the state with the corresponding React functions. You can find the Codepen here.

Force a React component to rerender

In the two years that I’ve been working with React professionally, I’ve never come to a point where I needed to force a re-render. I encourage you to read the article from the beginning if that’s what you’re here for because usually there’s a better way of dealing with React components that aren’t updating.

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

Using React’s forceUpdate function

This one is the most obvious one. In React class components, you can force 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 state with React.useState like this:

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. Remember: When the state of a component changes, all children will re-render.

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

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

Paints
0

Paints
0

Paints
0

Paints
0

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

Controlling when a component should update

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

Let’s have a look at them, after this, I’ll show you another, more effective way of improving render performance.

An example of this in action looks something like this:

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

This function is one of React’s lifecycle functions and allows us to optimize rendering performance by telling React when to update a class component.

Its arguments are the next props and the next state that the component is about to render:

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

Set the key attribute

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

Here I forgot to set the key attribute. Most linters will warn you about this, but why is it so important?

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

In the example above, if an event is being added to the beginning of the array, React will think that the first and all the subsequent elements have changed and will trigger a re-render of those. We can prevent this by adding a key to the element:

Structure of your components

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

Be careful where you place your logic. If you put everything in the root component of your application, all the React.memo functions in the world won’t help you to fix your performance problems.

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

Here’s how to force a re-render in React. ⚛

Hey there React developers! Do you struggle with unnecessary re-renders of components in your application?

We all must have gone through this phase when one component just keeps on updating its data in the background and then the overall performance takes a hit!

Most of the time when you start optimizing the code to the best of your knowledge you can assume that it is a very complex and tiring process because everything in React happens so fast when it updates the DOM.

Also, the fact that the DOM was updated doesn’t mean that it was actually modified by your changes. Well, then how do you stop this from happening or how would you rather force the Render? In this article, we’re about to see exactly how.

How to rerender component react. Смотреть фото How to rerender component react. Смотреть картинку How to rerender component react. Картинка про How to rerender component react. Фото How to rerender component react

That’s an impressive force!

A quick note on Render 📝

React’s createElement() function creates and returns a new element according to the element of the given type.

Render: this renders the React element into the DOM, returning a reference to the component. The output is taken from the createElement function.

Reconciliation: using the Diffing Algorithm, new elements are compared against previously elements and if there is a difference, the virtual DOM is updated.

Commit: finally, the stage where the real changes (DOM updation) are made.

Let’s see how the re-render is done in both the class and functional component types.

Forcing a re-render in a class component

Exit fullscreen mode

This is highly useful when the rendering depends on some other data apart from the state and you need React to re-render that specific component. The process is achieved by skipping the shouldComponentUpdate() lifecycle Hook.

Now, what is the solution then?

Re-render when state changes

The whole purpose of setState is to add changes in the queue to the component’s state and it tells React that this component and its children need to be re-rendered with the updated state. This takes in the following syntax:

Exit fullscreen mode

Let’s update the state of a component when it mounts.

Exit fullscreen mode

Here, we used the componentDidMount() lifecycle Hook to update the state.

Another example is for an event in a component:

Exit fullscreen mode

In this case, with the click of a button, we update the state.

Forcing a re-render in a functional component

Specifically, if we use the useState Hook, for a simple counter app, where on the onClick of a button, we increase the previous count inside the setter function of useState (for example: setCount ). This is exactly the point where we need to force the re-render of the counter component.

Here’s a relatable example:

Exit fullscreen mode

You can even go ahead and write your own custom Hook according to the need. It will work the same way just that this time you will have control over this Hook to add multiple points where you need a re-render.

Where to next? 🤔

Make your re-render count by visiting the following resources that talk more about different case scenarios and examples:

How to rerender component react. Смотреть фото How to rerender component react. Смотреть картинку How to rerender component react. Картинка про How to rerender component react. Фото How to rerender component react

Force Component to re-render With Hooks in React | by Harsh Patel | Weekly Webtips | Medium

Harsh Patel ・ Sep 29, 2020 ・

How to rerender component react. Смотреть фото How to rerender component react. Смотреть картинку How to rerender component react. Картинка про How to rerender component react. Фото How to rerender component react

How to rerender component react. Смотреть фото How to rerender component react. Смотреть картинку How to rerender component react. Картинка про How to rerender component react. Фото How to rerender component react

I have an external (to the component), observable object that I want to listen for changes on. When the object is updated it emits change events, and then I want to rerender the component when any change is detected.

With a top-level React.render this has been possible, but within a…

Thanks for reading, I appreciate it! Have a good day. (✿◕‿◕✿)

4 methods to force a re-render in React

How to rerender component react. Смотреть фото How to rerender component react. Смотреть картинку How to rerender component react. Картинка про How to rerender component react. Фото How to rerender component react

Are you looking to for a way to force a re-render on a React Component?

Here are a few methods to re-render a React component.

First, if you’re looking to become a strong and elite React developer within just 11 modules, you might want to look into Wes Bos, Advanced React course for just $97.00 (30% off). Wouldn’t it be nice to learn how to create end-to-end applications in React to get a higher paying job? Wes Bos, Advanced React course will make you an elite React developer and will teach you the skillset for you to have the confidence to apply for React positions.

Click here to become a strong and elite React developer: Advanced React course.

Disclaimer: The three React course links are affiliate links where I may receive a small commission for at no cost to you if you choose to purchase a plan from a link on this page. However, these are merely the course I fully recommend when it comes to becoming a React expert.

1. Re-render component when state changes

Any time a React component state has changed, React has to run the render() method.

In the example above I’m update the state when the component mounts.

You can also re-render a component on an event, such as a click event.

Both outputs will look like this:

2. Re-render component when props change

When the button gets clicked on it will update the component, and cause it to run the render() lifecycle again.

3. Re-render with key prop

I showed an example how to cause a re-render and run the componentDidMount() lifecycle, here.

By changing the value of the key prop, it will make React unmount the component and re-mount it again, and go through the render() lifecycle.

4. Force a re-render

This is a method that is highly discouraged. Always use props & state changes to cause a new render.

But nonetheless, here is how you can do it!

Conclusion

If you need to re-render a React component, always update the components state and props.

Try to avoid causing re-render with key prop, because it will add a bit more complexity. But There are odd use cases where this is needed.

Never use forceUpdate() to cause a re-render.

First, if you’re looking to become a strong and elite React developer within just 11 modules, you might want to look into Wes Bos, Advanced React course for just $97.00 (30% off). Wouldn’t it be nice to learn how to create end-to-end applications in React to get a higher paying job? Wes Bos, Advanced React course will make you an elite React developer and will teach you the skillset for you to have the confidence to apply for React positions.

Click here to become a strong and elite React developer: Advanced React course.

Disclaimer: The three React course links are affiliate links where I may receive a small commission for at no cost to you if you choose to purchase a plan from a link on this page. However, these are merely the course I fully recommend when it comes to becoming a React expert.

I like to tweet about React and post helpful code snippets. Follow me there if you would like some too!

How to rerender component react. Смотреть фото How to rerender component react. Смотреть картинку How to rerender component react. Картинка про How to rerender component react. Фото How to rerender component react

Ruben Leija

I launched this blog in 2019 and now I write to 85,000 monthly readers about JavaScript. Say hi to me at Twitter, @rleija_.

Do you want more React articles?

How and when to force a React component to re-render

September 8, 2021 4 min read 1255

How to rerender component react. Смотреть фото How to rerender component react. Смотреть картинку How to rerender component react. Картинка про How to rerender component react. Фото How to rerender component react

React usually automatically re-renders components, but for us to truly understand how and when to force React to re-render a component, we need to understand the inner workings of React.

Since the beginning of the web, we’ve used HTML and CSS to define the visual representation of a website. This has not changed, but, with the introduction of JavaScript, new concepts that enable us to read and update the rendered HTML of a page. We call this API DOM.

Libraries like jQuery became extremely popular because they provide an abstraction layer on top of the DOM API that provides enhanced functionality and compatibility, making it easy for developers to build web applications.

But jQuery has its limitations. It doesn’t solve crucial problems developers have when working with dynamically loaded content, such as keeping the JavaScript state (variables) and the DOM (HTML) in sync. Changing a variable in JavaScript does not affect the DOM directly.

Using a framework like React can solve this problem. React relies on JavaScript to maintain the state of an application. This master state object that contains a JavaScript reference to each object on the page is called Virtual DOM. Any changes on virtual DOM reflect automatically on the DOM, and that’s React’s best magic trick.

But how do we update the virtual DOM? We do this by building components and working with state and props.

The next question you may have is, what happens on the edge cases when a component is not updating as expected? Is it even possible? Maybe, but it’s complicated, so let’s discuss it.

Why aren’t React components re-rendering?

Generally, forcing a React component re-render isn’t best practice, even when React fails to update the components automatically. So, before considering forcing a re-render, we should analyze our code, as React magic depends on us being good hosts.

Incorrectly updated state in React

Here is a demonstration of the app with the complete code. You probably noticed that after clicking the button, nothing happens, even though we changed our state on the button:

How to rerender component react. Смотреть фото How to rerender component react. Смотреть картинку How to rerender component react. Картинка про How to rerender component react. Фото How to rerender component react

Over 200k developers use LogRocket to create better digital experiences

The component did not change, so there was no re-rendering trigger. Here’s why.

React evaluates state changes by checking its shallow equality (or reference equality), which checks to see if both the preview and new value for state reference the same object. In our example, we updated one of the properties of the user object, but we technically made setUser the same object reference, and thus, React didn’t perceive any change in its state.

State, as described in the React documentation, should be treated as immutable.

So, how do we fix it? We could create a new object with the correct values as follows:

Note that we are using the spread operator in JavaScript to preserve the properties of the original object while updating its name property under a new object. The final result can be observed here.

Incorrectly updated props without state change

While it may seem impossible, incorrectly updating props without a state change can happen, and it usually leads to bugs. Let’s look at an example.

In this demo, I built a clock that has a major problem: the time doesn’t change after I first load the screen. Not a very useful clock, right?

More great articles from LogRocket:

Let’s take a look at the code responsible for calculating the current time:

This demo doesn’t work because props are a reflection of state, so a standalone change in props won’t trigger a re-render. To fix it, we need a total rewrite.

Notice that we introduced state to manage myTime and useEffect to start and clear the timers to avoid bugs when the component re-renders. And it works!

Forcing a React component to re-render

It’s typically frowned upon to force a component to re-render, and the failure of automatic re-rendering in React is often due to an underlying bug in our codebase. But, if you have a legitimate need to force a React component to re-render, there are a few ways to do it.

Forcing an update on a React class component

If you are using class components in your code, you’re in luck. React provides an official API to force a re-render, and it’s straightforward to implement:

There are some caveats to this method:

Forcing an update on a function component

There’s no official API to re-render a function component, nor is there a React Hook. There are, however, some clever tricks to signal to React that a component should be updated.

Let’s say we want to force a refresh on our change user example above. We could do something like this:

Because user is an object, we could copy it to a new object and set it as the new state. The same could apply to any other object or array.

2. Have an empty state variable trigger updates

This method is interesting, as it creates a new object in the state. We only care about its update function as follows:

Here is an example of how to use it:

Now, each time we click on the Force Re-render button, the component will re-render. You can access the live demo here.

Conclusion

In general, we should prevent forcing React to re-render components. If React fails to do re-render components automatically, it’s likely that an underlying issue in your project is preventing the components from updating correctly.

However, we covered a few common ways to force React to re-render components should it be required. Happy coding!

Full visibility into production React apps

LogRocket is like a DVR for web and mobile apps, recording literally everything that happens on your React app. Instead of guessing why problems happen, you can aggregate and report on what state your application was in when an issue occurred. LogRocket also monitors your app’s performance, reporting with metrics like client CPU load, client memory usage, and more.

The LogRocket Redux middleware package adds an extra layer of visibility into your user sessions. LogRocket logs all actions and state from your Redux stores.

Modernize how you debug your React apps — start monitoring for free.

Источники информации:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *