If you wish for your request to truly only run once per lifecycle of your application, you can track whether the request began with a top-level variable. It sounds too simple, but it does meet the requirements.
This is also recommended in react.dev
let didInit = false;
function App() {
useEffect(() => {
if (!didInit) {
didInit = true;
// ✅ Only runs once per app load
loadDataFromLocalStorage();
checkAuthToken();
}
}, []);
// ...
}
I faced a similar issue when handling a code
query string parameter as part of OAuth2.0 response_type=code
response handling. I wanted to clear out the code
from the query string, but when my component was re-mounted as part of React 18's new StrictMode
behavior, I would not have the token response, or the code
query string, so the second time my component mounted it looked like a fresh load where I should redirect to my login page.
useRef
has a similar effect, but somehow feels MORE hacky. I suppose because it doesn't guarantee the same effect of having my code truly run only once per page load.