How to use useNavigate in combination with useEffect in React component to conditionally redirect when component renders?
Solution 1:
Is there a simple and "best-practice" way to solve this?
Yes! You can move the Router
higher in the ReactTree... higher than the component you want to use the navigate
function and provide a Context value you want to update.
const AppRouter = () => {
const navigate = useNavigate();
const [user, setUser] = useState<User | null>(null);
const context = useMemo<Context>(
() => ({ user: user, setUser: setUser }),
[user, setUser]
);
...
return (
<UserContext.Provider value={context}>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/test" element={<Test />} />
<Route path="/login" element={<Login />} />
<Route path="/register" element={<Register />} />
</Routes>
</UserContext.Provider>
);
};
...
<Router>
<AppRouter />
</Router>