JSPM

  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 41225
  • Score
    100M100P100Q165503F
  • License MIT

React hook for local-storage

Package Exports

  • @rehooks/local-storage

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (@rehooks/local-storage) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

npm version

@rehooks/local-storage

React hook for local-storage

Table of Contents

Install

With Yarn

yarn add @rehooks/local-storage

With NPM

npm i @rehooks/local-storage

Usage

Write to Storage

This can be anywhere from within your application.

import React from 'react';
import { writeStorage } from '@rehooks/local-storage';

let counter = 0;

const MyButton = () => (
  <button onClick={_ => writeStorage('i', ++counter)}>
    Click Me
  </button>
);

Read From Storage

This component will receive updates to itself from local storage.

import React from 'react';
import { useLocalStorage } from '@rehooks/local-storage';

function MyComponent() {
  const [counterValue] = useLocalStorage('i'); // send the key to be tracked.
  return (
    <div>
      <h1>{counterValue}</h1>
    </div>
  );
}

Delete From Storage

You may also delete items from the local storage as well.

import { writeStorage, deleteFromStorage } from '@rehooks/local-storage';

writeStorage('name', 'Homer Simpson'); // Add an item first

deleteFromStorage('name'); // Deletes the item

const thisIsNull = localStorage.getItem('name'); // This is indeed null

Full Example

import React from 'react';
import ReactDOM from 'react-dom';
import { writeStorage, deleteFromStorage, useLocalStorage } from '@rehooks/local-storage';

const startingNum = 0;

const App = () => {
  const [getNum, setNum] = useLocalStorage('num');

  return (
    <>
      <p>{getNum}</p>
      <button onClick={_ => setNum(getNum ? getNum + 1 : 0)}>Increment</button>
      <button onClick={_ => deleteFromStorage('num')}>Delete</button>
    </>
  );
};

// Assuming there is a div in index.html with an ID of 'root'
ReactDOM.render(<App />, document.getElementById('root'));