useState Hook Persist. Easily load stale from localStorage while revalidate.

栏目: IT技术 · 发布时间: 4年前

内容简介:A simple React Hook to persistWorks on the

Use State Persist

A simple React Hook to persist useState in local storage.

Works on the Web and React Native .

Easily implement

  • Offline state
  • Stale while revalidate flow
  • Global state
npm install use-state-persist
# or
yarn add use-state-persist

How to persists useState

Same behavior and API as useState so you can use it by easily replacing the useState hook for the calls which you want to persist offline.

import { useStatePersist as useState } from 'use-state-persist';

const Component = () => {
  // Before
  //const [counter, setCounter] = useState(0);
  const [counter, setCounter] = useState('@counter', 0);

  return <CounterDisplay value={counter} />;
};

Stale While Revalidate

import { useStatePersist as useState } from 'use-state-persist';

const Component = () => {
  // Loads stale state
  const [data, setData] = useState('@data');

  const fetchData = async () => {
    // Fetches new state
    const data = await fetch('/endpoint');
    setData(data);
  };

  useEffect(() => {
    fetchData();
  }, []);

  return <DataDisplay value={data} />;
};

Global State

Simple event system allows all the storage writes to be dispatched to all hooks . That means that all useStatePersist() can be used as a global state by sharing the same key useStatePersist('@globalKey')

To avoid that just make sure that the key being passed to the hook is unique useStatePersist('@uniqueKey')

const CounterButton = () => {
  const [counter, setCounter] = useState('@counter');

  return <Button onClick={() => setCounter(counter => counter++)} />;
};

State will be updated across multiple components

const ShowCounter = () => {
  const [counter, setCounter] = useState('@counter', 0);

  return <CounterDisplay value={counter} />;
};

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

生命3.0

生命3.0

[美] 迈克斯·泰格马克 / 汪婕舒 / 浙江教育出版社 / 2018-6 / 99.90元

《生命3.0》一书中,作者迈克斯·泰格马克对人类的终极未来进行了全方位的畅想,从我们能活到的近未来穿行至1万年乃至10 亿年及其以后,从可见的智能潜入不可见的意识,重新定义了“生命”“智能”“目标”“意识”,并澄清了常见的对人工智能的误解,将帮你构建起应对人工智能时代动态的全新思维框架,抓住人类与人工智能共生演化的焦点。 迈克斯·泰格马克不仅以全景视角探讨了近未来人工智能对法律、战争、就业和......一起来看看 《生命3.0》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

URL 编码/解码
URL 编码/解码

URL 编码/解码

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具