Rahul Saini

Some Techniques for Optimizing Performance on a React App

1. useMemo() –   is a built-in React hook that accepts 2 arguments — a function compute that computes a result and the dependencies array. 

Returns a memoized value.

Pass a “create” function and an array of dependencies. useMemo will only recompute the memoized value when one of the dependencies has changed. This optimization helps to avoid expensive calculations on every render.

Remember that the function passed to useMemo runs during rendering. Don’t do anything there that you wouldn’t normally do while rendering. For example, side effects belong in useEffect, not useMemo.

If no array is provided, a new value will be computed on every render.

Example of useMemo.

const memoizedList = useMemo(() => 

return userList.map(user => {

    return {

      …user,

      name: someExpensiveOperation(user.name)

    } 

  }) 

}, [userList])

2. useCallback() – useCallback hook is used when you have a component in which the child is rerendering again and again without need. 

Returns a memoized callback.

Pass an inline callback and an array of dependencies. useCallback will return a memoized version of the callback that only changes if one of the dependencies has changed. This is useful when passing callbacks to optimized child .components that rely on reference equality to prevent unnecessary renders (e.g. shouldComponentUpdate).

useCallback(fn, deps) is equivalent to useMemo(() => fn, deps).

Example of useCallback

function Parent() {

 const currentDate = 10/10/2020; 

 const someFn = () => {

     …

  };

  return(

    <Child someFn={someFn} currentValue = {currentDate }/>

  );

}

function Child({ someFn, currentDate }) { … };

 // Wrap function in useCallback() to prevent rerendering the child component 

 const someFn = useCallback(() => {

     …

  }, [dependencies]);

export default React.memo(Child)

3. React. Fragment –  Always use React.Fragment Tag to avoid the extra nodes to the DOM.

By using other tags like div, You are adding an extra node to the DOM, which is not necessary. In a case like this, where the above is a child component that will be enclosed within a parent component, this becomes a problem

React Fragment, does not added any additional node to the DOM.

You can also use the short syntax <>  </> for declaring a Fragment.

4. Lazy Loading – Lazy loading is a great technique for optimizing and speeding up the render time of your app.

The idea of lazy loading is to load a component only when it is needed. React comes bundled with the React.lazy API so that you can render a dynamic import as a regular component.

React.lazy takes a function that must call a dynamic import(). This will then return a Promise which resolves to a module with a default export containing a React component.

The lazy component should be rendered inside a Suspense component, which allows you to add fallback content as a loading state while waiting for the lazy component to load.

Example of Lazy Loading 

const UserProfile = React.lazy(() => import(‘./UserProfile.js’));

You use this lazy loaded component just like any other component:

function MyComponent() {

  // …

  return (

    <React.Fragment>

      {someCondition ? <UserProfile /> : null}

      <Route path=’/user-profile’ component={UserProfile}>

    </React.Fragment>

  );

}


5.React.memo()-  Avoid Re-rendering of components.

When a component is wrapped in React.memo(), React renders the component and memoizes the result. Before the next render, if the new props are the same, React reuses the memoized result skipping the next rendering.

Example of React.memo() 

export function Movie({ name, releaseDate }) {

  return (

    <div>

      <div>Movie title: {name}</div>

      <div>Release date: {releaseDate}</div>

    </div>

  );

}

export const MemoizedMovie = React.memo(Movie);

6. Avoid Using Inline Style Attribute- With inline styles, the browser spends a lot more time scripting and rendering.

A lot of time is spent on scripting because it has to map all the style rules passed to the actual CSS properties, which increases the rendering time for the component.

import React from “react”;

export default function InlineStyledComponents {

  render() {

    return (

      <>

        <b style={{“backgroundColor”: “black”}}>Welcome to Sample Page</b>

      </>

    )

  }

}

In the component created above, we have inline styles attached to the component. The inline style added is a JavaScript object instead of a style tag.

The style backgroundColor needs to be converted into an equivalent CSS style property and then the style will be applied. Doing so involves scripting and performing JavaScript execution.

The better way is to import the CSS file into the component.

Share