React Context Api vs Local Storage
Asked Answered
D

1

24

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?

Dagan answered 30/5, 2020 at 17:1 Comment(0)
A
59

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 recipe 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];
}
Akerley answered 30/5, 2020 at 17:22 Comment(3)
Thanks for the awesome answer so the best approach is combining both the context api for the app state and persist data with local storage which is needed even after refreshDagan
Combine local storage with any state managment, like context, yes.Akerley
Another reason to hydrate your UI state with the relevant local storage data in one place is that local storage might not be available in some cases, e.g. if your app is running in an iframe.Modred

© 2022 - 2024 — McMap. All rights reserved.