React
Performance
@jimeno0
Carlos P. Jimeno
( Some )
React Performance
- A performance note
- useMemo - expensive calculations
- memo & useCallback - avoid re-renders
- Tools
( some )
Quick note about performance
Thoughts about
const App = () => {
const [isActiave, setIsActive] = useState(false)
const handleToggle = useCallback(() => {
setIsActive(!isActive)
}, [])
return (
<Toggle onClick={handleToggle} isActive={isActive} />
)
}
React
is blazing fast
Profile before optimize
Please,
don't
over
engineer
Avoid expensive calculations
React.useMemo
useMemo
const App = ({ value }) => {
const result = React.useMemo(() => superExpensiveCalc(value), [value])
return (
<span>
The super expensive result is {result}.
</span>
)
}
Hands on
useMemo - recap
- Dependencies compares Object.is() (kind of ===)
- Stringify & parsing NOT the best option
- If non-primitive compares by reference
- Profile before optimize
- It doesnt have a registry of previous values other than the previos one
Avoid unnecessary
re-renders
React.Memo
React.memo
const ListItem = ({ name }) => {
return (
<li>
Super large or heavy list.
</li>
)
}
const MemoizedListItem = React.memo(ListLitem, (prevProps, nextProps) => {
return true;
});
Hands on
React.memo - recap
- Use state, external references or memoized values (useMemo || useCallback) as props.
- If non-primitive compares by reference
- Profile before optimize
- Take benefits from the comparative function
Further steps
- Virtualized DOM
- Code splitting & lazy loading
Toda optimización conlleva un coste
Optimiza con responsabilidad
🎉
References
react-performance
By Carlos Pérez Jimeno
react-performance
- 357