Skip to content
Advertisement

Unexpected output using react-router-dom with React’s Context API

For a small project of mine, I’m trying to implement the most basic authentication as possible, using the React context API without Redux.

JavaScript

I created a context, and wrapped my <App /> component in it like so; <AuthProvider></App></AuthProvider>. Because I want to keep the authenticated state, I used the browser’s local storage, for storing a simple boolean value.

JavaScript

Then, in my <App /> component, I tried invoking the login callback, given from the AuthProvider, which made me assume that made me login during page refreshes. When I try to access the authenticated variable in the current component, it does work. It shows that I am authenticated.

However when I try to set up a PrivateRoute, which only authenticated users can go to like this:

JavaScript

It does not work. It just redirects me to the login page. How does this come? The PrivateRoute component is getting rendered from the <App /> component. Also, what would be the solution to this problem?

Advertisement

Answer

Rather than running a useEffect on every rerender to check if user should be logged in, you should better initialize your authenticated state with the values from your localStorage:

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement