Currently, I’m looking for the best way to block or redirect users from accessing the login page if they are already logged in.
I’m working on a project using React with TypeScript.
What would be the best approach to implement this? Should I use Context API for managing authentication state, or would Redux be a better choice? Are there any other strategies or best practices I should consider for blocking the login page for authenticated users?
I made a custom hook that redirects me even if I’m logged in, it displays the page and then takes me back, is there any way to make it not render the page?
2
Answers
If you have a large application, I recommend saving the authentication state in Redux. You can store user information or tokens in browser cookies to persist them across browser refreshes.
You can then create a custom hook to manage redirection logic for both pages that require authentication and those that do not. Here’s a quick mockup for the custom hook:
You could consider making a HOC( Higher Order Component ) like PrivateRoute.jsx
and wrap your components around these where you want this functionality. The code will look something like this with context api.