Home > Blockchain >  Using local storage vs using useContext for auth token
Using local storage vs using useContext for auth token

Time:01-18

I'm new to React Native and have a fair amount of experience with React, but I still don't understand some fundamental concepts. One concept I don't understand is when to use local storage. I understand that local storage is used because it persists the data on the browser refresh, but if I were to use something like useContext to hold the user info and the auth token in a global state, then would that take the place of local storage, or do I still need to use local storage to hold it and if I do, then why? I'm asking this question for both React and React Native, as I'm trying to be proficient in both.

CodePudding user response:

useContext hook is used to create a global state that can be shared across multiple components. This can be used to store information such as the user's auth token, which can be used to fetch data from API but it will only persist as long as the user remains on the app. Once the user closes the app or refreshes the page, the global state will be lost.

You can use local storage to persist the user's auth token (stored in the browser) even after the user closes the app or refreshes the page. This way, when the user returns to the app, you can check if the auth token is still present in local storage, and if it is, you can automatically log the user back in without requiring them to enter their credentials again.

useContext to hold the user info and auth token in a global state can be useful for managing the user's session within the app, but it's not a replacement for local storage. Local storage is useful for persisting data across sessions, even when the user closes the app or refreshes the page.

Hope this gives you some clarity.

For more information on local storage, you can refer to the official documentation:

For React: https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

For React Native: https://reactnative.dev/docs/asyncstorage

And for more information on React useContext you can refer to: https://reactjs.org/docs/context.html

CodePudding user response:

useContext will not persistent data between refreshes, it simply avoids prop-drilling. A common pattern is to use the context as an accessor for an underlying store (such as localStorage) so that access is abstracted away from components.

Look at this answer for an example: https://stackoverflow.com/a/62505656/4088472

  • Related