I want to do this
useEffect(() => {
if (!datasetsState.list.length) {
dispatch({ type: DatasetsActionTypes.FETCH, payload: {} });
}
}, [datasetsState, dispatch]);
but dispatch({ type: DatasetsActionTypes.FETCH, payload: {} });
causes update of datasetsState
which will cause forever loop if datasetsState.list
stay empty after response
One of the solutions to my problem is to remove datasetsState
from the dependency array, but I will get react exhaustive-deps
warning which I want to avoid.
And the following code will work for me also and don't cause any warnings. But it is an ugly and complex solution for a pretty common problem I think.
const [isDoneOnce, setIsDoneOnce] = useState(false);
useEffect(() => {
if (isDoneOnce) {
return;
}
if (!datasetsState.list.length) {
dispatch({ type: DatasetsActionTypes.FETCH, payload: {} });
}
setIsDoneOnce(true);
}, [datasetsState, dispatch]);
How can I prevent useEffect
from updating without using additional variables like isDoneOnce
?