useContext hook in React

I’m working on a React project and I want to make it that when a user logs in, the app fetches that user data from the database and sets it to the User Context using useContext hook so that when the user goes to other pages, the user data will be available to that page to use. The problem is that when the user refreshes the page or go to other user-data dependent page, the user context is back to default and I would have to fetch the userdata again from the database for each page.
How can I make the context persisting over pages and after refresh ?

You can use local storage and there you can store a token generated by the server and you must check if it s valid(not expired) so you can grant the access to protected routes. You can also create a function when the web app loads that tries to get that token from local storage and validates it so the user is automatically logged in and also calculates for how long is valid before it expires(mostly tokens have an expiration time, like one hour or even more, like days, or tokens that auto refreshes so users don t have to login for weeks) and also automatically logs out the user if the token expires in the meantime. You might also need to have access to the user id.

1 Like

Cookie :cookie:

1 Like

If you want user data to persist offline (aka PWA) then IndexedDB:

1 Like