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

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

内容简介: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} />;
};

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

查看所有标签

猜你喜欢:

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

程序员面试手册

程序员面试手册

[印] 纳拉辛哈·卡鲁曼希(Narasimha Karumanchi) / 爱飞翔 / 机械工业出版社 / 2018-2-27 / 99

本书特色 以通俗易懂的方式讲述面试题,涵盖编程基础、架构设计、网络技术、数据库技术、数据结构及算法等主题 书中的题目来自微软、谷歌、亚马逊、雅虎、Oracle、Facebook等大公司的面试题,以及一些知名竞赛(如GATE)的考试题 全书约有700道算法题,每道题都有详细解答 针对每一编程问题,都会按照复杂度递减的顺序给出各种解法 专注于问题本身并对这些问题做出分析,......一起来看看 《程序员面试手册》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具