I would suggest using a state initializer function so you have correct initial state. You won't need to wait until a subsequent render cycle to have the correct authentication state.
const [isAuthenticated, setAuthenticated] = useState(() => {
const token = localStorage.getItem("AuthToken");
return token !== null;
});
The rest can likely remain the same.
I suggest you also provide a default context value as well.
const AuthContext = React.createContext({
isAuthenticated: false,
login: () => {},
});
export function useAuth() {
return useContext(AuthContext);
}
export const AuthProvider = ({ children }) => {
const [isAuthenticated, setAuthenticated] = useState(() => {
const token = localStorage.getItem("AuthToken");
return token !== null;
});
const login = () => setAuthenticated(true);
return (
<AuthContext.Provider value={{ isAuthenticated, login }}>
{children}
</AuthContext.Provider>
);
};
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…