How to force render and re-render your React components?

How to force render and re-render your React components?

Front-end technology has advanced dramatically in the previous ten years. Building a front-end web application is now more complex than it was previously. There are several front-end frameworks and libraries available today. Each library or framework has its own ways of doing things, such as rendering, processing updates, etc. In the React library, for example, there are a set of predefined methods for performing renders, processing updates, etc. React performs rerenders during the state, props, or element’s keys updates. But, in some situations, we need to rerender the component forcefully. To accomplish this, there are various solutions, which also includes methods provided by React, especially for this task.

In this article, we will learn various ways we can forcefully rerender a component. Following this article, you will also learn some crucial React fundamentals, such as the virtual DOM, React’s lifecycle model, etc.

What is a browser DOM?

DOM is an abbreviation for Document Object Model. It represents the HTML page as a node tree. The root node is the document, while the child nodes comprise the subtree. We may add, change, or remove items from the document using the DOM interface. When the DOM changes, the browser re-renders the UI.

What is a Virtual DOM?

The virtual DOM (or VDOM) is a fake version of the real browser DOM. It is an object designed to seem like the true DOM. Due to the fact that it does not write to the screen, the virtual DOM is less expensive to construct than the real DOM. The document exists as an object in memory rather than as HTML.

The React component lifecycle

In React, every component has a lifecycle consisting of 3 major steps: mounting, updating, and unmounting. These steps occur in order and define the steps every component in React goes through. Each step has its own importance, and these are one of the reasons React is so fast and efficient. Let us discuss each of these phases in more detail.

Mounting

Mounting is the process of constructing DOM nodes that correspond to Virtual DOM nodes. During the mounting process, React adds a component to the browser DOM that resides in the form of a Virtual DOM node in memory. We can see the component on the screen because of the mounting.

Updating

During the update phase, we may update the component’s state or props, which update the component’s return or the virtual DOM node corresponding to the component. React matches the new virtual DOM with the previous virtual DOM and applies only the necessary updates to the browser DOM. We also term this process of updating the component and applying the latest changes to the browser DOM as rerendering.

Unmounting

Like mounting, which is the process of adding a component that exists in the form of a Virtual DOM node in memory to the browser DOM, unmounting is the process is removing a component from the browser DOM. When the component unmounts, React removes the DOM node, as well as its children nodes, from the browser DOM and the Virtual DOM.

How to force rerender a React component?

As we already talked about, a React component rerenders when the component’s state, props, or element keys changes. To rerender a component forcefully, we must perform any one of the above actions. Apart from this, in class-based React components, React provides special methods for this purpose. This doesn’t mean that in class-based React components, we cannot achieve a forceful rerender by performing any of the above actions. But in the case of React functional components, we must perform any of the above actions manually.

Let us now look at various ways in which we can forcefully rerender a React component.

Forcefully rerender a class-based component using the forceUpdate method

If we are using a class-based React component, we can use the official method provided by React to rerender a component forcefully. The forceUpdate component will enable us to run the render function of the class. We may use it inside an event listener or a simple class method. It can be used as follows:

import React from 'react'

class ForceUpdateMethod extends React.Component {
  handleClick() {
    this.forceUpdate();
  }

  componentDidUpdate() {
    console.log('Rerender');
  }

  render() {
    return <button onClick={this.handleClick.bind(this)}>Button (forceUpdate method)</button>;
  }
}
Code language: JavaScript (javascript)

In the above code, we have created a method handleClick that calls the forceUpdate method. The method handleClick is bound to a button. We listen for rerenders using the componentDidUpdate method. Whenever we click the button, the component rerenders, and ‘Rerender’ gets logged onto the console.

Forcing rerender using the forceUpdate method.
Forcing rerender using the forceUpdate method.

There is also one limitation with this method. It cannot forcefully rerender the child components. The reason for it is that for child components, the shouldComponentUpdate method is also used, which prohibits the rerender. Therefore, it’s only useful for forcefully rerendering the current component.

Forcefully rerender a functional component by changing the component state

As we discussed previously, we may forcefully rerender a React component by changing its state. With functional components, to create a state, we use the useState hook. It returns an array consisting of the state and a function to update the state. In this case, we can keep the state values the same but instead place them in a new object so that React believes the values were changed and triggers a rerender. Let us look at the code to understand it better:

import React, { useState, useEffect } from "react";

function StateUpdate() {
  const [state, setState] = React.useState({value: 10});

  function forceUpdate () {
      setState(prev => {
          return {...prev}
      })
  }

  useEffect(() => {
    console.log('Rerender');
  })

  return (
    <button onClick={forceUpdate}>Button (State update)</button>
  );
}
Code language: JavaScript (javascript)

In the above code, we created a function rerenderForcefully, that will update the state. Inside the function, we used the setState function to update the component’s state. The function is bound to a button. We listen for rerenders using the useEffect hook. Whenever we click the button, the component is rendered, and ‘Rerender’ gets logged onto the console.

Forcing rerender using the useState hook.
Forcing rerender using the useState hook.

As you can see, we are not actually updating the values but just placing them inside a new object. By doing this, React thinks that the state has changed since the heap memory reference has changed with the new object.

Forcefully rerender a functional component by using a custom React hook

We can wrap the whole process we did earlier inside a custom React hook. Instead of coding logic for each component, we can just utilize the custom hook, making our code clearer and easier to comprehend. Hooks will also become more efficient with future React releases. Components, for example, might be folded before compilation.

Let us implement a custom hook to rerender a React component forcefully:

function useForceRerender() {
  const [state, setState] = React.useState({ value: 10 });

  function rerenderForcefully() {
    setState((prev) => {
      return { ...prev };
    });
  }

  return rerenderForcefully;
}Code language: JavaScript (javascript)

Our hook doesn’t take any arguments and returns a function, calling which our component will rerender. The logic we wrote inside the custom hook is the same logic we applied earlier.

We may import our custom React hook and use it inside any component as follows:

function StateUpdate() {
  const forceUpdate = useForceUpdate();

  useEffect(() => {
    console.log('Rerender');
  })

  return <button onClick={forceUpdate}>Button (Custom hook)</button>;
}
Code language: JavaScript (javascript)

A function is returned from the useForceUpdate hook. The function is bound to a button. We listen for rerenders using the useEffect hook. Whenever we click the button, the component is rendered, and ‘Rerender’ gets logged onto the console.

Forcing rerender using a custom hook.
Forcing rerender using a custom hook.

Conclusion

In the React library, there are a set of predefined methods for performing renders, processing updates, etc. React performs rerenders during the state, props, or element’s keys updates. To rerender a component forcefully, we must perform any one of the above actions. To forcefully rerender a class-based component, React provides a dedicated method called forceUpdate for this purpose. But for the functional components, we must perform the above functions in order to rerender. We can use the following three ways in which we can forcefully rerender a React component:

  1. Forcefully rerender a class-based component using the forceUpdate method.
  2. Forcefully rerender a functional component by changing the component state.
  3. Forcefully rerender a functional component by using a custom React hook.

Each method has its own advantages and disadvantages, but we may counter them by using some workarounds.

You can find the complete source code in Codedamn Playgrounds.

If you want to learn more about how React works under the hook, you can check out the following article by Codedamn:

React Internals Explained – How React works under the hood?

To learn more about some common issues that arise due to React’s lifecycle mode, you can check out the following article by Codedamn:

Can’t perform a react state update on an unmounted component: How to fix React error?

This article hopefully provided you with some new information. Share it with your friends if you enjoy it. Also, please provide your feedback in the comments section.

Thank you so much for reading 😄

Sharing is caring

Did you like what Varun Tiwari wrote? Thank them for their work by sharing it on social media.

0/10000

No comments so far