);
}
```
### 不要使用 `useRef` 来存储状态
避免使用 `useRef` 来存储状态。
如果想存储状态,应该使用 `useState` 或配合 `useAtomState` 的 Jotai 原子。
如果您觉得需要通过使用 `useRef` 来防止一些再渲染,请了解[如何管理再渲染](#managing-re-renders)。
## 管理再渲染
在 React 中管理再渲染可能很困难。
这里有一些规则以帮助避免不必要的再渲染。
请记住,通过了解其原因,可以**始终**避免再渲染。
### 在根级别工作
通过从根级消除它们,现在在新功能中避免再渲染变得容易。
The `PageChangeEffect` sidecar component contains just one `useEffect` that holds all the logic to execute on a page change.
这样您就知道只有一个地方可以触发再渲染。
### Always think twice before adding `useEffect` in your codebase
Re-renders are often caused by unnecessary `useEffect`.
You should think whether you need `useEffect`, or if you can move the logic in a event handler function.
You'll find it generally easy to move the logic in a `handleClick` or `handleChange` function.
您还可以在如 Apollo 的库中找到它们:`onCompleted`,`onError` 等。
### Use a sibling component to extract `useEffect` or data fetching logic
If you feel like you need to add a `useEffect` in your root component, you should consider extracting it in a sidecar component.
对于数据获取逻辑也可以采用相同的方法,使用 Apollo hooks。
```tsx
// ❌ 不佳:即使数据未发生变化也会导致重新渲染,
// 因为需要重新评估 useEffect
export const PageComponent = () => {
const [data, setData] = useAtomState(dataState);
const [someDependency] = useAtomState(someDependencyState);
useEffect(() => {
if(someDependency !== data) {
setData(someDependency);
}
}, [someDependency]);
return