This is the 8th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021
useMemo
UseMemo caches data
Performance optimization, caching data
- UseMemo behaves like calculated properties in Vue and can monitor changes in a value, and when the monitored value changes, a new value is calculated based on the change.
- UseMemo caches the results and does not recalculate even if the component is re-rendered if the monitored values do not change. This behavior can help avoid expensive calculations on each render.
export default function DemoMemo() { const [count, setCount] = useState(0) const [color, setColor] = useState('skyblue') const countDobule = useMemo(() => { console.log('memo... ') return count * 2 }, [count]) return ( <div> <h1>{count}</h1> <h2>{countDobule}</h2> <h4>{color}</h4> <button onClick={() => setCount(count + 1)} > count + 1 < / button > < button onClick = {() = > setColor (color + 'c')} > change color < / button > < / div >)}Copy the code
- CountDobule (countDobule); countDobule (countDobule); countDobule (countDobule); countDobule (countDobule); UseMemo will help us avoid some expensive calculations, caching data.
Insert the Memo method
The Memo method is used as a performance optimization for functional components.
Prevents component updates if the data in the component has not changed before rendering, similar to pureComponent in class components
Const Foo = memo(() => {console.log(' Foo component renders... ') return <div> foo </div>}) export default function MomoFn() {const [state, setState] = useState(0) return ( <div> <h1>{state}</h1> <button onClick={() => setState(state + 1)}>+1</button> <Foo /> </div> ) }Copy the code
When we change the data using setState, the MemoFn component is re-rendered, and Foo is not re-rendered if the component is wrapped in MOME.
useCallback
UseCallback caches functions
Performance optimized cache function
- The useCallback cache function allows the component to get the same function instance when it is re-rendered.
Const Foo = memo(props => {console.log(' Foo component render... ') return (<div> I am foo < buttonclick ={props. ResetCount}>resetCount</button> </div>)}) export default function DemoCallback() { const [state, setState] = useState(0) const resetCount = useCallback(() => setState(0), [setState]) return ( <div> <h1>{state}</h1> <button onClick={() => setState(state + 1)}>+1</button> <Foo resetCount={resetCount} /> </div> ) }Copy the code
- UseCallback is generally used when passing functions to sub-components. To avoid re-rendering of sub-components, the function instance is cached so that the same function instance is rendered each time. Achieve the purpose of performance optimization.