Best practice: prepare props only once for rendering

107 views Asked by At

Consider the following simple page in a nextjs app:

type MyProps = {
    myData: string[]
}

export const getServerSideProps: GetServerSideProps<MyProps> = async ({ req, res }) => {
    return { props: {myData: calcData()} }
}

function MyComponent(props: MyProps) {
   return <div>{props.myData}</div>
}

What is the best practice to prepare data in props? In my case I need to sort data according to a criteria that is not present on server-side code (current language in client-side browser, using next-i18next). I could use state like

function MyComponent(props: MyProps) {
   const [sortedProps] = useState({myData: props.myData.sort(...)})

   return <div>{sortedProps.myData}</div>
}

but that doesn't sound "intended by React" for me. Maybe useEffect(() => {...}, []) that runs once is a better choice? If yes, how do I remember the resulting data from useEffect? useRef?

EDIT: Or is useMemo the way to go?

1

There are 1 answers

1
maya_nk99 On

You can use lazy initial state as follows:-

const [state, setState] = useState(() => {
  const initialState = someExpensiveComputation(props);
  return initialState;
});


Ref: https://reactjs.org/docs/hooks-reference.html#lazy-initial-state