DEV Community

Bryan Liao
Bryan Liao

Posted on • Originally published at bryanliao.dev

Building in Public - 5

I added the use of localStorage to my React project. Since my app is client-only, it felt like the right thing to do to allow some data persistence.

I created two functions: one to load data from localStorage and another one to add data. The key-value pairing in localStorage is just strings, so I had to use JSON.stringify() and JSON.parse() to manipulate the data:

const context = {...};
localStorage.setItem('appData', JSON.stringify(context));

const localData = localStorage.getItem('appData');
if(localData){
const parsedData = JSON.parse(localData);
...
}
Enter fullscreen mode Exit fullscreen mode

Initially I was calling the add data function in my form submissions, but since I was using React I found it easier to use stick it in useEffect instead. Using the existing data as a dependency, I could update localStorage any time it changed.

I also called my data loading function within useEffect. I used useRef to determine the first render in order to swap between loading previously saved data and updating localStorage when the data changed. Hooray for data persistence 🎉

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more