DEV Community

Cover image for Persistence Pays Off: React Components with Local Storage Sync 🔄🦸🏻‍♂️

Persistence Pays Off: React Components with Local Storage Sync 🔄🦸🏻‍♂️

Matt Lewandowski on July 13, 2024

Have you ever spent minutes creating the perfect response only to lose it all with a misclick or accidental refresh? We often focus on optimizing p...
Collapse
 
y2x profile image
2X Y

just did same thing here

const useStateWithLocalStorage = <T>(
  key: string,
  initialValue: T,
): [T, React.Dispatch<React.SetStateAction<T>>] => {
  const [value, setValue] = useState<T>(() => {
    const localStorageValue = localStorage.getItem(key);
    if (localStorageValue !== null) {
      return localStorageValue;
    } else {
      return initialValue;
    }
  });
  useEffect(() => {
    localStorage.setItem(key, value);
  }, [value]);

  return [value, setValue];
};
Enter fullscreen mode Exit fullscreen mode
Collapse
 
phil_johnston profile image
Phil Johnston

Definitely need to include security in the considerations, as private data should never persist to local storage.

Collapse
 
mattlewandowski93 profile image
Matt Lewandowski

Good point, thanks I'll add it in.

Collapse
 
phil_johnston profile image
Phil Johnston

🙌 nice work

Collapse
 
sumitsaurabh927 profile image
Sumit Saurabh

Excellent article and I don't wanna highjack the comment section but what do you use for product notification in React? Like if I'm building an app in React, what are some of the tools/libraries I can use to embed notifications in my app?

Collapse
 
karlatt profile image
karlatt • Edited

You can enhance the whole process and speed, by dedicating to a web-worker to all the serialisation/deserialisation and write/read work, creating a homeMade Store (with a BehaviorSubject and a Map<> to store the data, for exemple) as a runtime cache, so you can pool the hard work (thinking at the web worker like a thread). The Web-Worker fills the cache on request, or automatically (for referenceData, like all the countries, etc ..), and you get your data from the "store", which is instant in normal conditions. Did that at work, it's working wonderfully ;) . EDIT : For security, a simple crypto algorithm is enough : localStorage is ...local, so you don't have a lot of people that will access directly to your computer/browser, and of course, you'll never persist sensitive data here : if you REALLY need to (you'll never !!), you can encrypt with an enormous key, you can use any cloud based secret-Vault to get your keys and all that. If somebody is smart enough to take the control of your working computer from an outside location, the "poorly" encrypted data that you have in your localStorage will be the least of your preoccupations :)

Collapse
 
jonahunuafe profile image
Jonah Unuafe

Why not writing simple react code without adding typescript? Not everyone understands typescript.

Collapse
 
russpalms profile image
RussPalms

Because type safety is important even with simple implementations.

Collapse
 
karlatt profile image
karlatt

they should ;)

Collapse
 
d4r1ing profile image
Nguyễn Thế Cuân

You might need to listen "storage" event and update component state accordingly, as we can always change local storage directly.

Collapse
 
mattlewandowski93 profile image
Matt Lewandowski

Not in this case. We are using local storage for a back up. If our main goal was to sync state between windows, I’d use something like the BroadcastChannel API.