9

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.

NearHuscarl
  • 66,950
  • 18
  • 261
  • 230
  • 1
    Related answer: https://stackoverflow.com/questions/57220059/internal-implementation-of-makestyles-in-react-material-ui/57226057#57226057 – Ryan Cogswell Mar 12 '20 at 11:06

1 Answers1

10

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} />;
}
Barun Patro
  • 860
  • 4
  • 13
  • thank you for replying,so it is a successor which returns a hook by using inbuilt-hook(under hood)? how would i know what it takes as argument , what it returns and what is design pattern of doing this? – Parsuram Kailasa Mar 12 '20 at 10:30
  • 2
    So as you can see.. it takes a simple argument, an object of class names, with their styles.. So its basically styles represented in SCSS.. It is an CSS in JS kind of approach. you can use styles in your component with out any external stylesheets(css or scss) – Barun Patro Mar 12 '20 at 10:35
  • 1
    @BarunPatro "a CSS in JS kind of approach" ... this reads like a reinvention of [JSSS](https://en.wikipedia.org/wiki/JavaScript_Style_Sheets) to me ;-) – orithena Jan 14 '22 at 16:49
  • 1
    dear barun, thank you for your efforts. please avoid the many "just" "basically" "simply" - it improves your posts. – citykid Aug 30 '22 at 20:34