Languages
[Edit]
EN

React - custom useLocalStorage hook

3 points
Created by:
Rubi-Reyna
677

In this article, we would like to show you how to create a custom hook to save data in local storage under React application.

Quick solution:

 

Practical example

Edit

In this example, we present a practical example of how to use useLocalStorage() custom hook to store data in local storage.

There are two basic concepts in this solution:

  1. useEffect inside the useLocalStorage hook is responsible for setting the key/value pair inside the local storage,
  2. getSavedValue method is a getter for data saved in the local storage by key.

Note: local storage stores values as trings. This is the reason why JSON.parse() to get the value and JSON.stringify() to set value are used.

Result:

Custom useLocalStorage hook in React.
Custom useLocalStorage hook in React.

References

Edit
  1. Window.localStorage - Web APIs | MDN
  2. Storage.getItem() - Web APIs | MDN
  3. Storage.setItem() - Web APIs | MDN

Alternative titles

  1. React - custom hook to use local storage
  2. React - custom hook to save data in local storage
1
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join