Based on the article outlined in the React docs: You Might Not Need An Effect, they explain that logic which should only be executed once should be wrapped in an init clause.
i.e.
// Will run init flow only once per application lifecycle
let didInit = false;
function App() {
useEffect(() => {
if (!didInit) {
didInit = true;
loadDataFromLocalStorage();
checkAuthToken();
}
}, []);
}
Or:
// Will run init flow whenever component is mounted
function App() {
const didInit = useRef(false);
useEffect(() => {
if (!didInit.current) {
didInit.current = true;
loadDataFromLocalStorage();
checkAuthToken();
}
}, []);
}
However, if moved outside the effect, the behavior remains the same. So if the behavior’s the same, why would you need the hook?