Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

184
Views
Memoize a function in React

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?

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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.
about 4 years ago · Juan Pablo Isaza Report

0

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 initialized only once and the returned memonized function is used in subsequent function calls.

const specialFunction = useCallback((index) => {
    switch (index) {
    case 0:
      return <Component0 />;
    case 1:
      return <Component1 />;
    case 2:
      return <Component2 />;
    default:
      return null;
    }
  }, []);
about 4 years ago · Juan Pablo Isaza Report

0

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>
     ...
  );

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!