阻止组件重新渲染
2024-01-10 本文已影响0人
海豚先生的博客
重新渲染的起因:
- 组件的state变化
- 父组件重新渲染
- 组件使用context,provider的value发生变化时
子组件使用useContext导致的重渲染
// value是个复杂类型的对象,父组件的重渲染会导致重新生成{mode}
const ThemeContext = React.createContext<Theme>({ mode: 'light' });
const useTheme = () => {
return useContext(ThemeContext);
};
// before:
// 父组件
const [mode, setMode] = useState<Mode>("light");
return (
<ThemeContext.Provider value={{ mode }}>
// 这里有个计数器点击+1
// 这里有个按钮可以切换主题模式
</ThemeContext.Provider>
);
const Item = ({ country }: { country: Country }) => {
// 父组件计数器+1,这里每次会是个新对象,导致重渲染
const { mode } = useTheme();
const className = `country-item ${mode === "dark" ? "dark" : ""}`;
// the rest is the same
}
// after:
const [mode, setMode] = useState<Mode>("light");
// memoising the object! 缓存对象
const theme = useMemo(() => ({ mode }), [mode]);
return (
<ThemeContext.Provider value={theme}>
<button onClick={() => setMode(mode === 'light' ? 'dark' : 'light')}>Toggle theme</button>
// 这里有个计数器,可以点击+1
// 这里有个按钮可以切换主题模式
</ThemeContext.Provider>
)
// 子组件
const Item = ({ country }: { country: Country }) => {
// 父组件计数器+1,这里每次是个同一个对象,不会重渲染
// 切换主题会导致子组件重新渲染
const { mode } = useTheme();
const className = `country-item ${mode === "dark" ? "dark" : ""}`;
// the rest is the same
}
React.memo,将组件缓存
// 只要props中的属性(a,或者其他更多的参数)没有变化,MovingComponent 的重渲染不会导致ChildComponent 的重渲染
// 如果props中有函数参数,在父组件中应使用useCallback包裹,以保持父组件每次重渲染时,传递给子组件的函数引用地址一致
const ChildComponent = (props) {
...
return (
<div onClick={props.onClick}>{props.a}</div>
)
}
export default React.memo(ChildComponent)
const MovingComponent = () => {
const [state, setState] = useState({ x: 100, y: 100 });
const onClick = useCallback(() => {
console.log('xxx')
}, [])
return (
<div
onMouseMove={(e) => setState({ x: e.clientX - 20, y: e.clientY - 20 })}
style={{ left: state.x, top: state.y }}
>
// MovingComponent的重渲染不会导致ChildComponent 的重渲染
<ChildComponent a={111} onClick={onClick} />
</div>
);
};
抽离为children,以避免重渲染
# 鼠标移动后,MovingComponent 会重渲染,导致子组件ChildComponent 重渲染,如果后者很“重”,将导致性能问题
const MovingComponent = () => {
const [state, setState] = useState({ x: 100, y: 100 });
return (
<div
// when the mouse moves inside this component, update the state
onMouseMove={(e) => setState({ x: e.clientX - 20, y: e.clientY - 20 })}
// use this state right away - the component will follow mouse movements
style={{ left: state.x, top: state.y }}
>
<ChildComponent />
</div>
);
};
// ChildComponent 通过children 传递,MovingComponent 的重渲染不会导致ChildComponent 重渲染,因为ChildComponent 隶属于组件SomeOutsideComponent,组件作为children传递不会重渲染,因为它是props,它在SomeOutsideComponent 组件中已经创建完毕,已经调用过React.createElement了
const MovingComponent = ({ children }) => {
const [state, setState] = useState({ x: 100, y: 100 });
return (
<div onMouseMove={(e) => setState({ x: e.clientX - 20, y: e.clientY - 20 })} style={{ left: state.x, top: state.y }}>
// children now will not be re-rendered
{children}
</div>
);
};
const SomeOutsideComponent = () => {
return (
<MovingComponent>
<ChildComponent />
</MovingComponent>
);
};
Mystery 1: why components that are passed as props don’t re-render?
为什么通过props传递一个组件,父组件重渲染不会使该组件重渲染?
Answer 1: “children” is a <ChildComponent /> element that is created in SomeOutsideComponent. When MovingComponent re-renders because of its state change, its props stay the same. Therefore any Element (i.e. definition object) that comes from props won’t be re-created, and therefore re-renders of those components won’t happen.
Mystery 2: if children are passed as a render function, they start re-rendering. Why?
为什么将props.children通过一个函数传递,会导致重渲染?
const MovingComponent = ({ children }) => {
// this will trigger re-render
const [state, setState] = useState();
return (
<div ///...
>
<!-- those will re-render because of the state change -->
{children()}
</div>
);
};
const SomeOutsideComponent = () => {
return (
<MovingComponent>
{() => <ChildComponent />}
</MovingComponent>
)
}
Answer 2:In this case “children” are a function, and the Element (definition object) is the result of calling this function. We call this function inside MovingComponent, i.e. we will call it on every re-render. Therefore on every re-render, we will re-create the definition object <ChildComponent />, which as a result will trigger ChildComponent’s re-render.
Mystery 3: MovingComponentMemo使用memo,为什么没有阻止由于SomeOutsideComponent 重渲染导致ChildComponent 的重渲染
// wrapping MovingComponent in memo to prevent it from re-rendering
const MovingComponentMemo = React.memo(MovingComponent);
const SomeOutsideComponent = () => {
// trigger re-renders here with state
const [state, setState] = useState();
return (
<MovingComponentMemo>
<!-- ChildComponent will re-render when SomeOutsideComponent re-renders -->
<ChildComponent />
</MovingComponentMemo>
)
}
const MovingComponent = ({children}) => <>{children}</>
Answer 3:因为SomeOutsideComponent 的每次重渲染都重新创建了ChildComponent (是个对象),MovingComponentMemo会检查props是否变动,即检查props.children,因为ChildComponent 是重新生成的,与之前的不相等(2个对象的地址不相等),所以会触发重渲染;如果将ChildComponent 使用memo包裹,则MovingComponent的重渲染不会导致ChildComponent 重渲染,因为MovingComponent检查发现这个props与之前的相等
Mystery 4: when passing children as a function, why memoizing this function doesn’t work?
将Mystery 2中的函数使用useCallback包裹,还是阻止不了重渲染?
const SomeOutsideComponent = () => {
// trigger re-renders here with state
const [state, setState] = useState();
// this memoization doesn't prevent re-renders of ChildComponent
const child = useCallback(() => <ChildComponent />, []);
return <MovingComponent>{child}</MovingComponent>;
};
const MovingComponent = ({ children }) => {
// this will trigger re-render
const [state, setState] = useState();
return (
<div ///...
>
<!-- those will re-render because of the state change -->
{children()}
</div>
);
};
child函数被记忆,但是它的返回结果(<ChildComponent />)没有被记忆,同一个函数每次都会执行React.createElement,即重渲染
参考
https://www.developerway.com/posts/react-elements-children-parents