React hooks: useSessionStorage and useLocalStorage
Saulo Dias

Saulo Dias @saulodias

About: Software Developer graduated in Automation and Control Engineering trying way too hard to become a brogrammer.

Location:
Rio de Janeiro, Brazil
Joined:
Apr 29, 2021

React hooks: useSessionStorage and useLocalStorage

Publish Date: Jul 1 '22
19 3

I needed a simple way to use the sessionStorage and localStorage with React, and one of the requirements was to use TypeScript. The idea from Robin Wieruch's original article is pretty simple. It encapsulates the browser sessionStorage or localStorage with the useState hook. The hooks actually return a stateful value, and a function to update it. All I had to do was to put everything together into a TypeScript module.

You can also customize the STORAGE_KEYS_PREFIX, which can be useful to avoid conflicts between storage keys from different applications you might be developing.

If you like this post, you'll also like:

Comments 3 total

Add comment