P粉8348408562023-08-19 00:29:53
Yes, this is correct. Each render creates a new function, which is then replaced by the cached function.
The speedup is not due to skipping the step of creating the function, but because other code is able to skip their own work. This is because if they are passed the same function every time, they know that nothing relevant has changed.
For example, if you need to pass handleChange
to the dependency array of useEffect
, it is very important to pass a stable reference every time, otherwise the effect will be passed every time it is rendered. Rerun:
useEffect(() => { // ... 使用handleChange做一些事情 }, [handleChange]);
Alternatively, if handleChange
is passed as a prop to a component and the component wants to skip rendering using React.memo
. Rendering can be skipped only when props have not changed:
const Parent = () => { const handleChange = useCallback((ev) => { setMsg(ev.target.value); }, []); return <Child handleChange={handleChange}/> } const Child = React.memo(({ handleChange }) => { // ... 使用handleChange做一些事情 })