Recoil 是 React 的一个状态管理库,它提供了一种简洁的方式来管理 React 应用的状态。Recoil 的最新一个版本是 2023年3月1日发布的 0.7.7。 2025年1月1日,Recoil 已经被作者归档。

Recoild 应用示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import React from 'react';
import { RecoilRoot, atom, selector, useRecoilState, useRecoilValue } from 'recoil';

// 将 RecoilRoot 设置为根组件
function App() {
return (
<RecoilRoot>
<CharacterCounter />
</RecoilRoot>
);
}

// atom 代表一个状态。atom 可在任意组件中进行读写。读取 atom 值的组件隐式订阅了该 atom,因此任何 atom 的更新都将致使使用对应 atom 的组件重新渲染
const textState = atom({
key: 'textState', // 唯一 ID (相对于其它 atoms/selectors)
default: '' // 默认值 (也被称为初始值)
});

function CharacterCounter() {
return (
<div>
<TextInput />
<CharacterCount userID={123} />
</div>
);
}

// 在需要使用的组件中,引入 atom 并使用 useRecoilState()
function TextInput() {
const [text, setText] = useRecoilState(textState);

const onChange = event => {
setText(event.target.value);
};

return (
<div>
<input type='text' value={text} onChange={onChange} />
<br />
Echo: {text}
</div>
);
}

// selector 代表一个派生状态,派生状态是状态的转换。你可以将派生状态视为将状态传递给以某种方式修改给定状态的纯函数的输出
const charCountState = selector({
key: 'charCountState', // 唯一 ID (相对于其它 atoms/selectors)
get: ({ get }) => {
const text = get(textState);

return text.length;
}
});

// 如果希望基于参数进行查询,而不仅仅是基于派生状态。例如,需要根据组件的 props 来查询时可以使用 selectorFamily helper 来实现
const userNameQuery = selectorFamily({
key: 'UserName',
get: userID => async () => {
const response = await myDBQuery({ userID });
if (response.error) {
throw response.error;
}
return response.name;
}
});

// 使用 useRecoilValue() 的 来读取 selector 的值
function CharacterCount({ userID }) {
const count = useRecoilValue(charCountState);
const userName = useRecoilValue(userNameQuery(userID));

return (
<>
<div>Character Count: {count}</div>
<div>{userName}</div>
</>
);
}