INTRO 🔔
Hello World! 👋
Today we are discussing another custom hook named useLocal🔥.
NOTE📌 : Technically, this one can't be considered as a hook 🙃 because, as per the custom hook definition, i
f we create one function using React hooks, then it is called a Custom Hook🙂. But in this code, we are not using any React hooks 😕. So we can't call it a custom hook 😟, but for our convenience, we are now considering it as a custom hook 😉.
USAGE 🔔
If you are a Frontend Developer🧑🏻💻, you must know the Local Storage📦 & Session Storage📦. These are browser properties that help to store and access the data in sessions.
Every time using local storage for getting data as localStorage.getItem('item') and for setting data as localStorage.setItem('item', data) is very lengthy, and it is not readable. To overcome this problem, we created a helper(custom hook) called useLocal (particularly for localStorage)
CODE 🔔
export const useLocal = (itemName) => {
const setLocal = (data) => {
localStorage.setItem(itemName, JSON.stringify(data));
};
const getLocal = () => {
return JSON.parse(localStorage.getItem(itemName));
};
const removeLocal = () => {
localStorage.removeItem(itemName);
};
return [setLocal, getLocal, removeLocal];
}
USE CASE 🔔
import React, { useEffect } from "react";
import { useLocal } from "./useLocal";
function Index() {
const [setLocal, geLocal, removeLocal] = useLocal("app_token");
useEffect(() => {
setLocal("k8axga83alf991z90a9a0aaf1");
return () => removeLocal();
}, []);
const handleGet = () => {
const token = geLocal();
console.log(token);
};
return (
<div>
<button onClick={handleGet}>Get Token</button>
</div>
);
}
export default Index;
CONCLUSION 🔔
By using the same method, we can create a custom hook for Session Storage also.
I hope this post gives you some information. We will meet in the next post with another new custom hook.
Peace 🙂