内容简介: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} />; };
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
数据挖掘十大算法
(美)吴信东(Xindong Wu)、(美),库玛尔 ,(Vipin Kumar) / 李文波、吴素研 / 清华大学出版社 / 2013-5 / 39.00元
《世界著名计算机教材精选:数据挖掘十大算法》详细介绍了在实际中用途最广、影响最大的十种数据挖掘算法,这十种算法是数据挖掘领域的顶级专家进行投票筛选的,覆盖了分类、聚类、统计学习、关联分析和链接分析等重要的数据挖掘研究和发展主题。《世界著名计算机教材精选:数据挖掘十大算法》对每一种算法都进行了多个角度的深入剖析,包括算法历史、算法过程、算法特性、软件实现、前沿发展等,此外,在每章最后还给出了丰富的习......一起来看看 《数据挖掘十大算法》 这本书的介绍吧!