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?
You can use lazy initial state as follows:-
Ref:
https://reactjs.org/docs/hooks-reference.html#lazy-initial-state