React Custom Hooks (useLocal)
sundarbadagala
Posted on April 30, 2024
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
If 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 one 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 next post with another new custom hook.
Peace π
Posted on April 30, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 27, 2024