Home > OS >  Memoize a function in React
Memoize a function in React

Time:11-11

There is a component that receives props.

The props has the shape of an array, for each element of this array, a function is going to return a different component to render.

function MainComponent ({ data }) => { // data is props, an array

  const specialFunction = (index) => {
    switch (index) {
    case 0:
      return <Component0 />;
    case 1:
      return <Component1 />;
    case 2:
      return <Component2 />;
    default:
      return null;
    }
  };
  ...
  return (
     ...
     data.map((item, index) => {
        ... // do other stuff with item
        <div>{specialFunction(index)}</div> // the function that we talk about
   
     ...
  );

Is there a way to memoize the result of this if the props is not going to change? Or any way to write it better?

CodePudding user response:

Other pattern, I think in this case the most elegant is to use:

const components = {
   0: <Component0 />,
   1: <Component1 />,
   2: <Component2 />,
}

/*
or
const components = [<Component0 />, <Component1 />, <Component2 />]
*/

function MainComponent ({ data }) => {
  ...
  return (
     ...
     data.map((item, index) => 
        <div>{components[index] || null}</div>
     ...
  );

CodePudding user response:

There are a couple of way to achieve this:

  1. You could use a state to store the array

const [components] = useState([<Component0 />, <Component1 />, <Component2 />])

And then just use components[index] when trying to render.

  1. You could try useCallback to memoize your function.

CodePudding user response:

useCallback with empty dependency array will be the best approach here. useCallback will return a memoized version of the callback that only changes if one of the dependencies has changed. Since our dependeny array is [] it will be executed only once and the function will be memonized.

const specialFunction = useCallback((index) => {
    switch (index) {
    case 0:
      return <Component0 />;
    case 1:
      return <Component1 />;
    case 2:
      return <Component2 />;
    default:
      return null;
    }
  }, []);
  • Related