I have created AuthContext that holds currently logged in user:
// auth-context.ts
export interface IAuthContext {
auth: IMe | null;
setAuth: (user: IMe | null) => void;
}
const AuthContext = React.createContext<IAuthContext>({
auth: null,
setAuth: (auth: IMe | null) => {}
});
export default AuthContext;
The simplified main rendered App component where I use the context provider looks like this:
const App: FC = () => {
const [auth, setAuth] = useState<IMe | null>(null); // problematic line
return (
<AuthContext.Provider value={{auth, setAuth}}>
<BrowserRouter>
<Routes>
<Route path='/' element={<Main/>}/>
<Route path="/login" element={<Login/>}/>
<Route path="/register" element={<Register/>}/>
<Route path="/about" element={<About/>}/>
</Routes>
</BrowserRouter>
</AuthContext.Provider>
);
}
Overall, the application works fine.
However, when I navigate the application by manual URL changes in the web browser, followed-up by hitting the Enter (therefore: page refresh), then there is a problem with auth context reset to null...
I think when I change the URL manually then the whole App component is re-rendered and therefore the AuthContext state is reseted to null by the problematic line.
The idea is that the Login component is using the setAuth inside of it after the form-related promise is positively resolved.
Any tip how can I protect myself from that re-render problem, and therefore context resettng to default null value? I think this scenario is kind of basic, but I am beginner in frontend stuff. Thank you!