I have two components that interact with each other via Redux state. One component (ComponentA) authorizes a user action to "override" something, sets Redux state to indicate the user is authorized to "override" and then redirects to another component (ComponentB). ComponentB checks the Redux state to see if the user is authorized and, if so, allows the user to do so. ComponentB has a "useEffect" cleanup function with no dependencies that runs when the component is unmounted that sets the Redux state to indicate the user is no longer authorized to "override".
The issue with React StrictMode is that it is calling the "useEffect" cleanup function twice (by design). The first time the "useEffect" cleanup function runs, it sets the Redux state to indicate the user is no longer authorized to "override" (i.e. state.event.overrideAuthorized = false). Then on the second render of ComponentB, it finds that state.event.overrideAuthorized = true and redirects the user elsewhere, thinking the user isn't authorized.
This logic works fine without React StrictMode as the cleanup only runs once when ComponentB unmounts after the authorized user has done what they need to do or navigates away from page without doing anything. But I cannot figure out a way to get this working with React StrictMode.
Pseudo-code:
const ComponentA = () => {
...
const handleSubmit = ({ pin }) => {
dispatch(authorizeOverride(event, pin)).then(() => navigate("./componentB");
// authorizeOverride sets Redux state.event.overrideAuthorized=true
};
...
};
const ComponentB = () => {
...
const authorized = useSelector(state => state.event.overrideAuthorized);
useEffect(() => {
return () => {
if (authorized) dispatch(overrideComplete());
/// overrideComplete sets Redux state.event.overrideAuthorized=false
}
}, []);
if (!authorized) navigate('/home');
// Render component to allow user to do something when they are authorized to override
...
};
Any ideas how to refactor this to work with React StrictMode? With React StrictMode enabled, the second render of ComponentB always navigates to '/home' since state.event.overrideAuthorized is false due to the "useEffect" cleanup function running after the first render.