DEV Community

Cover image for React Custom Hooks (useLocal)
sundarbadagala
sundarbadagala

Posted on

React Custom Hooks (useLocal)

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];
}
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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 ๐Ÿ™‚

Top comments (0)