in this post, I’ll create a custom hook to use LocaleStorage with react. The localStorage is used to store temporary data into the browser memory.
I will create a simple example to read and write data into local storage using reactjs.
The localStorage is a common mechanism of a browser’s web storage. It allows users to save data as key–value pairs in the browser for later use.
We can access a browser’s Storage object via localStorage. The Storage object includes methods for saving, reading, and removing data, among other things.
There are two variant of local storage available:
- sessionStorage : The Session storage data is available only to the same browser window
- localStorage : The data is available in browser windows with the same origin (domain)
Prerequisites:
– Basic understanding of React and React Hooks.
– Node.js installed on your computer.
Simple Example Localstorage with React Hooks
The React hooks allow building components by using functions instead of classes. They also give us the ability to have state in functional components.
How to Set Value In Local Storage Using React
You can use setItem(key, val)
method to store the data into localstorage. The first param is the key and second is the value of data.
The Syntax:
localStorage.setItem("key", "value")
Only data-type strings are accepted in the browser store. As a result, we must use JSON.stringify()
to convert values of various data kinds, such as objects or arrays, to a JSON string.
You can see simple example below:
const [name, setName] = useState("phpflow"); function setName(value) { localStorage.setItem(key, JSON.stringify(value)); }
Reading data from the localStorage
The getItem(key)
method is used to get the stored data of HTML5 local storage. The param 'key'
is the key name of the data.
You can see simple example below:
function getStorageValue(key, defaultValue) { // getting stored value if (typeof window !== "undefined") { const data = localStorage.getItem(key); const initialData = data !== null ? JSON.parse(data) : defaultValue; return initialData; } }
We have used JSON.parse()
method to deserialize the returned JSON string from the local storage.
Remove data from localStorage Using AngularJS
You can also remove data from the localStorage.
You can see simple example below:
localStorage.removeItem('name');
ReactHooks for LocalStorage
Let’s create a custom Hook to persist form inputs in multiple components.
import { useState, useEffect } from "react"; function getValue(key, value) { // getting stored value const data = localStorage.getItem(key); const initialValue = JSON.parse(data); return initialValue || value; } export const useTmpStorage = (key, value) => { const [value, setValue] = useState(() => { return getStorageValue(key, value); }); useEffect(() => { // storing input name localStorage.setItem(key, JSON.stringify(value)); }, [key, value]); return [value, setValue]; };
How To use custom Hook in React
Let’s create a component and use custom localStorage hooks to set data into storage:
import { useTmpStorage } from "../Helper/useTmpStorage"; const TaskStatus = () => { const [status, setStatus] = useLocalStorage("status", "Pending"); }
Checkout Other Localstorage tutorials,