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)