git clone https://github.com/ericmasiello/react-performance-talk
cd react-performance-talk
npm i
npm start
Render as fast as possible by running the least code as possible
// Dynamic import
import('/some-module.js').then(
module => {
// do stuff with the module's exports
},
error => {
// there was some error loading the module...
},
)
// Static import
import SomeModule from '/some-module.js';
// smiley-face.js
import React from 'react'
function SmileyFace() {
return <div>😃</div>
}
export default SmileyFace
// ------------------------------------------
// app.js
import React from 'react'
const SmileyFace = React.lazy(() => import('./smiley-face'))
function App() {
return (
<div>
<React.Suspense fallback={<div>loading...</div>}>
<SmileyFace />
</React.Suspense>
</div>
)
}
Extra Credit:
Figure out how to precache MomentBoy before the user clicks on "Show"
"Render" phase
"Reconciliation" phase
"Commit" phase
State change
New props passed
Subscribed context updates
Parent component (re)renders
Rerenders are not necessarily expensive
Rerenders do not necessarily lead to a commit
Measure, measure, measure!
function Distance({x, y}) {
const distance = calculateDistance(x, y)
return (
<div>
The distance between {x} and {y} is {distance}.
</div>
)
}
Allows expensive functions to only re-evaluate when dependencies changes
function Distance(props) {
const {x, y} = props;
const distance = React.useMemo(
() => calculateDistance(x, y),
[x, y]
);
return (
<div>
The distance between {x} and {y} is {distance}.
</div>
);
}
Can be used to ensure a value's reference does not change
const Theme = React.createContext({});
function ThemeProvider(props) {
const [color, setColor] = useState('#333');
const [bgColor, setBgColor] = useState('#fff');
const themeValue = useMemo(() => ({
color,
setColor,
bgColor,
setBgColor,
}), [color, bgColor]);
return (
<Theme.Provider value={themeValue}>
{props.children}
</Theme.Provider>
);
}
* Components that render {children} are difficult to optimize using the above: https://github.com/facebook/react/issues/8669
import React from 'react';
const Name = React.memo(
function Name(props) {
return (
<p>Your name: {props.first} {props.last}</p>
);
}
);
export default Name;