I have some general questions which are bothering me regarding the context API and local storage.
When to use local storage?, when to use the Context API and when would I use both?
I know that to persist data after the refresh I need something like local storage or session storage, so do I ditch the context API entirely and just store everything in the local storage? this way I can not only store data but also keep it on refresh? some insight would be really helpful.
What are some pros and cons?
Context API vs Local storage is apples vs oranges comparison.
Context API is meant for sharing state in the component tree.
Context provides a way to pass data through the component tree without having to pass props down manually at every level.
Local Storage is for storing data between sessions.
The read-only localStorage property allows you to access a Storage object for the Document's origin; the stored data is saved across browser sessions.
The right comparison might be Local Storage vs Cookies, Context API vs State-Management Library (not really, since Context is not a state management tool).
While you can store everything on the local storage (although it's not scalable and maintainable) it won't be useful.
It won't be useful because you can't notify your components on state change, you need to use any React's API for it.
Usually local storage is used for session features like saving user settings, favorite themes, auth tokens, etc.
And usually, you read once from local storage on application start, and use a custom hook to update its keys on related data change.
Here is a helpful receipt for useLocalStorage
custom hook:
function useLocalStorage(key, initialValue) {
// State to store our value
// Pass initial state function to useState so logic is only executed once
const [storedValue, setStoredValue] = useState(() => {
try {
// Get from local storage by key
const item = window.localStorage.getItem(key);
// Parse stored json or if none return initialValue
return item ? JSON.parse(item) : initialValue;
} catch (error) {
// If error also return initialValue
console.log(error);
return initialValue;
}
});
// Return a wrapped version of useState's setter function that ...
// ... persists the new value to localStorage.
const setValue = value => {
try {
// Allow value to be a function so we have same API as useState
const valueToStore =
value instanceof Function ? value(storedValue) : value;
// Save state
setStoredValue(valueToStore);
// Save to local storage
window.localStorage.setItem(key, JSON.stringify(valueToStore));
} catch (error) {
// A more advanced implementation would handle the error case
console.log(error);
}
};
return [storedValue, setValue];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With