7th Practical Class:
More Hooks, forwardRef, memo
Some More Hooks
useMemo
,useCallback
- Custom Hooks
useRef
(focus)
useMemo
, useCallback
Whithout Memoization:
function SomeComponent({ a, b, onSubmit }) {const sum = a + b;const submitCallback = () => onSubmit(a, b);return (<button type="button" onClick={submitCallback}>{sum}</button>);}
With Memoization:
function SomeComponent({ a, b, onSubmit }) {const sum = useMemo(() => {return a + b;}, [a, b]);const memoizeMe = () => onSubmit(a, b);const submitCallback = useCallback(memoizeMe, [a, b]);return (<button type="button" onClick={submitCallback}>{sum}</button>);}
React.memo
- Use React.memo() wisely
- ๐งโ use
React.memo
only when something becomes slow - ๐งโ overuse of
React.memo
will make your app much slower! - remember: Premature optimization is the root of all evil
- same is for
useMemo
anduseCallback
- use it only when needed
- same is for
- ๐งโ use
0
Rerender ๐
NoRerender ๐
Rerender
NoRerender
Custom Hooks
- see Building Your Own Hooks
- use
use*
prefix!
useRef
React.forwardRef
React.forwardRef
documentation- allows you to use
ref
in custom components
Focus does not work in this example. For fix see example below.
Enable ref
for custom component: