Using the makeStyles / useStyles() pattern causes React apps to render twice
See original GitHub issueLet me start by saying, I ❤️ MUI. K, lets dive in:
I log how frequently my react app renders, just so I maintain fine grain control over DOM renders / reflows. I noticed whenever I start my react app, it rendered twice at the root level. I began investigating the root cause and I’ve narrowed it down to:
import React from "react";
import { makeStyles } from "@material-ui/core/styles";
export default ()=> {
const classes = useStyles();
};
const useStyles = makeStyles(()=> { ... });
This causes react apps to render twice. Here’s the thing, on the first render, classes
is fully populated and ready to go. The second render returns the same classes
object, with no differences --> thus the second re-render is unneeded and wasteful.
Current Behavior 😯
See above ^
Expected Behavior 🤔
const classes = useStyles()
does not effect component re-rendering.
Using withStyles
instead of makeStyles
(which have the same outcome of making a classes
object available), DOES NOT cause the component to render twice. It’s expected the makeStyles
and withStyles
do not effect rendering. withStyles
is working that way, makeStyles
is not.
Steps to Reproduce 🕹
See the codesandbox links below for evidence of the issue:
makeStyles renders twice withStyles renders once
As you can see, withStyles
has the correct behavior, and makeStyles
, has the buggy behavior.
Context 🔦
Rendering apps twice costs:
- money
- wastes user resources
- wastes planetary resources
Ask yourself, if you were Captain Picard, what would you do in this situation? 😆
Your Environment 🌎
Tech | Version |
---|---|
Material-UI | v4.9.8 |
React | 16.13 |
Browser | Chrome 80 |
Issue Analytics
- State:
- Created 3 years ago
- Reactions:3
- Comments:5 (3 by maintainers)
Top GitHub Comments
@NawarA ⚠️ This double rendering is a development only behavior. It won’t happen in production.
Proof: https://codesandbox.io/s/strictmode-w-and-wo-hooks-vex1m deployed in production: https://csb-vex1m.netlify.com/.
This codesandboxes use StrictMode (see index.js) which calls render twice. Depending on your component tree this causes issues if you have side effects during render (such as console.log or
++renderCount
)Not necessarily. What we care more in react are commits and even more is actual performance measurements. Render counting is a tool to identify issues but it does not necessarily imply you have a performance issue.