npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

react-session-hooks

v1.0.8

Published

Easily synchronize your React state with session storage using type-safe hooks.

Downloads

673

Readme

react-session-hooks

A lightweight React library providing custom hooks for managing state synchronized with localStorage and sessionStorage that works with Server Side Rendering frameworks.

Table of Contents

Installation

To install the library, use npm or yarn:

npm install react-session-hooks

or

yarn add react-session-hooks

Ensure you also have React as a peer dependency:

npm install react

Usage

useLocalState

The useLocalState hook allows you to manage state that persists across page reloads using localStorage.

  • It includes a listener to maintain synchronization.
  • It will return null if there is any error in serializing or deserializing data.
  • It will remove the item from storage if the value is set to undefined, null, or "".
import { useLocalState } from "react-session-hooks";

const MyComponent = () => {
  const [value, setValue, loading] = useLocalState("myKey", "default");

  if (loading) return <div>Loading...</div>;

  return (
    <div>
      <p>Current value: {value}</p>
      <button onClick={() => setValue("newValue")}>Update Value</button>
    </div>
  );
};

useSessionState

The useSessionState hook allows you to manage state that persists only within the current browser session using sessionStorage.

  • It includes a listener to maintain synchronization.
  • It will return null if there is any error in serializing or deserializing data.
  • It will remove the item from storage if the value is set to undefined, null, or "".
import { useSessionState } from "react-session-hooks";

const MyComponent = () => {
  const [value, setValue, loading] = useSessionState("myKey", "default");

  if (loading) return <div>Loading...</div>;

  return (
    <div>
      <p>Current value: {value}</p>
      <button onClick={() => setValue("newValue")}>Update Value</button>
    </div>
  );
};

API

useLocalState API

const [storedValue, setStoredValue, loading] = useLocalState<T>(
  key: string,
  defaultValue?: T,
  serialize?: (value: T) => string,
  deserialize?: (value: string) => T
);

Parameters

  • key (string): The key under which the value is stored in localStorage.
  • defaultValue (T, optional): The default value to use if no value is found in localStorage.
  • serialize ((value: T) => string, optional): Custom serialization function.
  • deserialize ((value: string) => T, optional): Custom deserialization function.

Returns

  • storedValue: The current value stored in localStorage.
  • setStoredValue: A function to update the stored value.
  • loading: A boolean indicating whether the hook is currently loading the initial value.

useSessionState API

const [storedValue, setStoredValue, loading] = useSessionState<T>(
  key: string,
  defaultValue?: T,
  serialize?: (value: T) => string,
  deserialize?: (value: string) => T
);

Parameters

  • key (string): The key under which the value is stored in sessionStorage.
  • defaultValue (T, optional): The default value to use if no value is found in sessionStorage.
  • serialize ((value: T) => string, optional): Custom serialization function.
  • deserialize ((value: string) => T, optional): Custom deserialization function.

Returns

  • storedValue: The current value stored in sessionStorage.
  • setStoredValue: A function to update the stored value.
  • loading: A boolean indicating whether the hook is currently loading the initial value.

Example Scenarios

useLocalState example

Here’s a simple example of using useLocalState to manage a user’s preferred language setting:

import { useLocalState } from "react-session-hooks;

const LanguageSelector = () => {
  const [language, setLanguage, loading] = useLocalState(
    "preferredLanguage",
    "English"
  );

  if (loading) return <div>Loading...</div>;

  return (
    <div>
      <p>Selected language: {language}</p>
      <button onClick={() => setLanguage("English")}>English</button>
      <button onClick={() => setLanguage("Spanish")}>Spanish</button>
    </div>
  );
};

useSessionState Example

As shown previously, useSessionState can be used in a form to manage user input within a session:

import { useSessionState } from "your-library-name";

const MyForm = () => {
  const [formValue, setFormValue, loading] = useSessionState("formData", "");

  if (loading) return <div>Loading...</div>;

  const handleChange = (event) => {
    setFormValue(event.target.value);
  };

  return (
    <form>
      <input type="text" value={formValue} onChange={handleChange} />
      <button type="submit">Submit</button>
    </form>
  );
};

Contributing

If you'd like to contribute to this project, please follow these steps:

  1. Fork the repository.
  2. Create a new branch for your feature or bug fix.
  3. Make your changes and commit them.
  4. Push to your branch and open a pull request.

License

This project is licensed under the MIT License. See the LICENSE file for details.