[英]react hooks avoid re-render and keep required deps
I missed something with useEffect, useCallback and deps.我错过了 useEffect、useCallback 和 deps 的一些东西。
I have one context and one component.我有一个上下文和一个组件。 My component load every data I need with fetch() and set a boolean to true in the context to show a spinner.我的组件使用 fetch() 加载我需要的所有数据,并在上下文中将 boolean 设置为 true 以显示微调器。 I use the context in another component when I need it.当我需要时,我会在另一个组件中使用上下文。
const LoadingApp = ({children}) => {
const loadingContext = useContext(LoadingContext);
const fetchMyData = useCallback(() => {
loadingContext.setLoading(true);
}, [loadingContext]);
useEffect(() => {
fetchMyData();
}, [fetchMyData]);
return (
<React.Fragment>
{children}
</React.Fragment>
);
};
const LoadingProvider = ({children}) => {
const [loading, setLoading] = useState(false);
const setLoading = useCallback((isLoading) => {
setLoading(loading + (isLoading ? 1: -1));
}, [setLoading, loading]);
const isLoading = useCallback(() => {
return loading > 0;
}, [loading]);
return (
<LoadingContext.Provider value={{setLoading, isLoading}}>
{children}
</LoadingContext.Provider>
)
}
I know I could remove the deps from useEffect or useCallback but it seems to be the wrong way to fix my issue as deps is required.我知道我可以从 useEffect 或 useCallback 中删除 deps,但这似乎是解决我的问题的错误方法,因为需要 deps。
How could I call a function in a context in a useEffect or useCallback without re-rendering everything?如何在 useEffect 或 useCallback 的上下文中调用 function 而无需重新渲染所有内容?
If you are calling setLoading
, then you are always going to trigger a rerender which is what you want.如果您正在调用setLoading
,那么您总是会触发您想要的重新渲染。
You could have an empty deps
, which means the effect will only run once.你可以有一个空的deps
,这意味着效果只会运行一次。
The context always changes when the loading
value changes.当loading
值改变时,上下文总是改变。 Change the dependencies of useEffect
to only depend on setLoading
, which is based on useCallback
( useState
setter doesn't change as well), and will stay fixed.将useEffect
的依赖项更改为仅依赖于setLoading
,它基于useCallback
( useState
setter 也不会更改),并且将保持固定。
const { setLoading } = useContext(LoadingContext);
const fetchMyData = useCallback(() => {
setLoading(true);
}, [setLoading]);
You don't actually need the useCallback
, since it does the same thing that the original setLoading
is doing.您实际上并不需要useCallback
,因为它与原始setLoading
所做的事情相同。 You can safely remove this:您可以安全地删除它:
const setLoading = useCallback((isLoading) => {
setLoading(isLoading);
}, [loading]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.