How to style components using makeStyles and still have lifecycle methods in React Material UI?

To style components using makeStyles and still have lifecycle methods in React Material UI, we call makeStyles outside our component.

And then we use the useStyles hook returned from makeStyles to apply the styles.

For instance, we write

import React, { useEffect, useState } from "react";
import axios from "axios";
import { Redirect } from "react-router-dom";

import { Container, makeStyles } from "@material-ui/core";

import LogoButtonCard from "../molecules/Cards/LogoButtonCard";

const useStyles = makeStyles((theme) => ({
  root: {
    display: "flex",
    alignItems: "center",
    justifyContent: "center",
    margin: theme.spacing(1),
  },
  highlight: {
    backgroundColor: "red",
  },
}));

const Welcome = ({ highlight }) => {
  const [userName, setUserName] = useState("");
  const [isAuthenticated, setIsAuthenticated] = useState(true);
  const classes = useStyles();

  //...
  if (!isAuthenticated()) {
    return <Redirect to="/" />;
  }
  return (
    <Container
      maxWidth={false}
      className={highlight ? classes.highlight : classes.root}
    >
      <LogoButtonCard
        buttonText="Enter"
        headerText={isAuthenticated && `Welcome, ${userName}`}
        buttonAction={login}
      />
    </Container>
  );
};

export default Welcome;

to call makeStyles with an object with the class names set to objects with the styles for each class name.

Then we call useStyles in Welcome to return the classes object.

And then we apply the styles to Container from the classes object in the className prop.