What exactly is makeStyles in material-ui?

Viewed 5909

I just started learning React material-ui and I found this makeStyles function, and they said it returns a Hook.

I remember from React hooks that a custom hook is made by wrapping a built-in hook. I tried looking inside makeStyles, and it has some interoperability and some css-in-javascript pattern.

I am really fed up with rules coming over and over again. For now can someone please tell me what is this makeStyle function and perhaps suggest a better approach to reading about material-ui.

Thank you good people of Stack Overflow.

1 Answers

If you are familiar with the older version of Material-UI, you might have used withStyles, to use your custom styles in MUI components.

withStyles is just a HOC(Higher Order Component), used as a wrapper, to assign the classes prop to your component. You can furthur use the classes object to assign specific classes to your DOM or MUI elements in your component.

makeStyles is just a successor, which returns a hook(to access the custom classes). Now this is only a modern-react way of doing things in order to avoid HOCs.

MUI v3.9.3

import { withStyles } from '@material-ui/core/styles';

const styles = {
  root: {
    backgroundColor: 'red'
  },
};

class MyComponent extends React.Component {
  render () {
    return <div className={this.props.classes.root} />;
  }
}

export default withStyles(styles)(MyComponent);

MUI v4.9.5

import React from 'react';
import { makeStyles } from '@material-ui/core/styles';

const useStyles = makeStyles({
  root: {
    backgroundColor: 'red'
  },
});

export default function MyComponent(props) {
  const classes = useStyles(props);
  return <div className={classes.root} />;
}
Related