skip to Main Content

I am relatively new to React, and still have not full familiarity with this thing to re-render components every time a state changes.
I understand that re-renders make declarative components possible, but in terms of performance it seems less than optimal, and I have trouble determining when component re-render is to be avoided.

Let’s say I have a render-costly component RenderCostlyComponent with a loading state that applies a class to it to show loading is in progress.

function RenderCostlyComponent(props) {

    const [loading, setLoading] = useState(true);
    const [componentData, setComponentData] = useState({});

    //Data retrieval or calculation and store in 'componentData' data state

    return (
        <div className={loading ? 'loadingClass' : ''}>
            {/*Comoponent layout here*/}
        </div>
    );

}

In this case, just to change a class (or in other cases where minimal changes are applied), the component needs to re-render. Surely no data has changed so React won’t rebuild the heavy DOM parts, especially if we’ve been using memoization related hooks.

But is this approach practical and production ready or this should be considered a bad practice?

2

Answers


  1. Although the question is a bit unclear but react re-rendering process is quite a powerful feature and in most cases its impact on performance is negligible.However, if you want to optimise the code more consider:

    1. Use React.memo which is a Higher order component to make a pure component in react.
    2. Use useMemo and useCallback hooks that will help in memoizing the values of js functions.

    React process of reconciliation is very efficient therefore re-rendering is practical and production ready approach.

    Login or Signup to reply.
  2. There is a concept of component trees.
    If you have a container which renders based on a state and you have a heavy content which you do not want react to visit each time your container rerenders, you can use children prop on container component.

    const Container = () => {
      const [state, setState] = useState()
    
      return <div>{children}</div>
    }
    
    const SomeHeavyComponent = () => {}
    
    const Page = () => {
      return <Container><SomeHeavyComponent /></Container>
    }
    

    This way the app won’t visit when the state in Container changes.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search