React Context Api vs Local Storage

12,344

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];
}
Share:
12,344
Steytz
Author by

Steytz

Updated on July 21, 2022

Comments

  • Steytz
    Steytz almost 2 years

    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?

  • Steytz
    Steytz almost 4 years
    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 refresh
  • Dennis Vash
    Dennis Vash almost 4 years
    Combine local storage with any state managment, like context, yes.
  • Nick Bernard
    Nick Bernard over 2 years
    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.