Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

The difference : put Material-UI MakeStyles const outside vs inside functional component

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading