Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixes #63- Add useLocalStorage Custom hook #64

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

rray524
Copy link
Collaborator

@rray524 rray524 commented Nov 5, 2024

Checklist:

  • Added useLocalStorage custom hook ( adding, set new value & reset/remove options enabled )

Resolves #63

How to use this useLocalStorage hook?

Usage Example of Theme Toggling:

import React from "react";
import useLocalStorage from "./useLocalStorage";

function ThemeToggle() {
  const [darkMode, setDarkMode, removeDarkMode] = useLocalStorage("darkMode", false);

  const toggleTheme = () => {
    setDarkMode((prev) => !prev);
  };

  const resetTheme = () => {
    removeDarkMode(); // This will clear the value from localStorage and reset the state
  };

  return (
    <div className={`app-container ${darkMode ? "bg-gray-800 text-white" : "bg-white text-gray-800"} min-h-screen flex flex-col items-center justify-center`}>
      <h1 className="text-2xl font-bold mb-4">Theme Toggle with useLocalStorage</h1>
      <p className="text-lg mb-6">
        Toggle between light and dark themes. Your preference will be saved!
      </p>
      <button
        className={`px-4 py-2 rounded focus:outline-none transition duration-300 ${
          darkMode ? "bg-gray-700 hover:bg-gray-600" : "bg-gray-200 hover:bg-gray-300"
        }`}
        onClick={toggleTheme}
      >
        Switch to {darkMode ? "Light" : "Dark"} Mode
      </button>
      <button
        className="mt-4 px-4 py-2 bg-red-500 text-white rounded focus:outline-none"
        onClick={resetTheme}
      >
        Reset Theme Preference
      </button>
    </div>
  );
}

export default ThemeToggle;

Description

useLocalStorage is a custom React hook that simplifies storing and retrieving values from localStorage. It synchronizes state with localStorage, allowing data to persist across page reloads. The hook provides three functions: get to retrieve the stored value, set to update it, and remove to clear the value from storage and reset the state. This ensures a seamless experience for saving user preferences or other persistent data.

References

image

@rray524 rray524 requested a review from rt4914 November 5, 2024 23:45
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

[Feature Request]: Create useLocalStorage hook
2 participants