when I use MATERIAL-UI, I found I can also define the const useStyles inside the functional components:
import React, { useEffect, useState } from 'react';
import { Container, makeStyles } from '@material-ui/core';
const Welcome = ({highlight}) => {
const useStyles = makeStyles(theme => ({
root: {
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
},
}));
const [isAuthenticated, setIsAuthenticated] = useState(true);
const classes = useStyles();
return (
<div> ... </div>
)
I wonder is it better to write const useStyles outside the welcome Function component or they are the same thing in terms of performance ?
Thank you
CodePudding user response:
There are few things to consider. Firstly, result of work done in makeStyles
can be shared between multiple instances of the same component, but when you call it in a function component you are doing same work multiple times (performance penalty). Secondly, there are multiple objects created in makeStyles
body, so calling it on every render will cause garbage collection pauses more often (performance penalty). Thirdly, there is a deep merge operation, which also costs more than usual comparison or assignment (another performance penalty).
If you want to know more, open https://github.com/mui/material-ui/blob/v4.x/packages/material-ui-styles/src/makeStyles/makeStyles.js for source code of this function.
Taking into consideration these facts there is basically no reason to call makeStyles
in your function component. That's why it's never invoked like this in Material-UI docs.
CodePudding user response:
I'm not to familiar with makeStyles
(and as it is deprecated it seems to be a good idea to replace that anyway), but in general if no useMemo
(or similiar) hook is used the assigement of these values is done on each render, which is no problem at first, but can potentially pile up and waste time.
Therefore either put them outside the functional component or use an apropriate hook to store the result between renders. I'd suggest doing the later as it still keeps it in the react loop, and makes it possible to ocassionally recreate the values if a dependency of the memorized computation has changed.