We know that useMemo and useCallback are mainly used to cache intermediate states and reduce meaningless render to improve performance. But recently I have found that I have been misunderstanding their use! misunderstanding of useMemo Please take a look at the following code. Even with useMemo , the second subcomponent is re-rendered without the change of isZero ! import { useCallback, useMemo, useState } from "react"; const Child = ({ value, onClick }) => { return ( <div style={{ height: 100, background: `#${(~~(Math.random() * (1 << 24))).toString(16)}` }} > my value is {value.toString()} </div> ); }; export default function App() { const [count, setCount] = useState(0); const isZero = useMemo(() => !!(count % 3), [count]); const onClick = useCallback(() => setCount(count + 1), [count]); return ( <div className="App"> <button onClick={onClick}>click me</button> <Child value={count} /> <Child value={isZero} /> </div> ); } 💡 related reading in fact, the reason has also been mentioned in previous articles: React every time the state of a component changes, it starts from the current component until all leaf node components are re-rendered. The article also mentions the solution to this problem: the subcomponent is wrapped with the memo function, and the component can render as expected. however, at this point we remove useMemo , and the subcomponents are still rendered as expected. memo is similar to useMemo , which is based on a shallow comparison of Object.is and is only valid for non-reference types. so in the above example, it makes no sense to use useMemo . misunderstanding of useCallback however, in the above example, the…

June 6, 2023 0comments 1269hotness 0likes Aaron Read all