or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

tessl/npm-recoil

Recoil is an experimental state management framework for React applications that provides atoms and selectors for fine-grained reactivity.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/recoil@0.7.x

To install, run

npx @tessl/cli install tessl/npm-recoil@0.7.0

0

# Recoil

1

2

Recoil is an experimental React state management framework that provides fine-grained reactivity through atoms (units of state) and selectors (derived state). It offers minimal boilerplate with automatic optimization, where components only re-render when specific state they depend on changes, and includes built-in support for asynchronous operations and concurrent React features.

3

4

## Package Information

5

6

- **Package Name**: recoil

7

- **Package Type**: npm

8

- **Language**: JavaScript with Flow types and TypeScript definitions

9

- **Installation**: `npm install recoil`

10

11

## Core Imports

12

13

```typescript

14

import {

15

RecoilRoot,

16

atom,

17

selector,

18

useRecoilState,

19

useRecoilValue,

20

useSetRecoilState

21

} from "recoil";

22

```

23

24

CommonJS:

25

```javascript

26

const {

27

RecoilRoot,

28

atom,

29

selector,

30

useRecoilState,

31

useRecoilValue,

32

useSetRecoilState

33

} = require("recoil");

34

```

35

36

## Basic Usage

37

38

```typescript

39

import React from 'react';

40

import {

41

RecoilRoot,

42

atom,

43

selector,

44

useRecoilState,

45

useRecoilValue,

46

} from 'recoil';

47

48

// Define atoms (state)

49

const textState = atom({

50

key: 'textState',

51

default: '',

52

});

53

54

// Define selectors (derived state)

55

const charCountState = selector({

56

key: 'charCountState',

57

get: ({get}) => {

58

const text = get(textState);

59

return text.length;

60

},

61

});

62

63

// Component using Recoil state

64

function TextInput() {

65

const [text, setText] = useRecoilState(textState);

66

return (

67

<input

68

value={text}

69

onChange={(e) => setText(e.target.value)}

70

/>

71

);

72

}

73

74

function CharacterCount() {

75

const count = useRecoilValue(charCountState);

76

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

77

}

78

79

// App with RecoilRoot

80

function App() {

81

return (

82

<RecoilRoot>

83

<TextInput />

84

<CharacterCount />

85

</RecoilRoot>

86

);

87

}

88

```

89

90

## Architecture

91

92

Recoil is built around several key concepts:

93

94

- **Atoms**: Fundamental units of state that components can read from and write to

95

- **Selectors**: Pure functions that transform state or compute derived state

96

- **RecoilRoot**: Context provider that manages the state graph and subscriptions

97

- **Hooks**: React hooks for reading and writing state with automatic subscriptions

98

- **State Graph**: Directed graph where atoms are source nodes and selectors are derived nodes

99

- **Fine-grained Subscriptions**: Components only re-render when specific state they depend on changes

100

- **Concurrent Mode Support**: Built-in compatibility with React's concurrent features

101

102

## Capabilities

103

104

### Root Provider

105

106

Core component for managing Recoil state throughout your React application.

107

108

```typescript { .api }

109

interface RecoilRootProps {

110

initializeState?: (mutableSnapshot: MutableSnapshot) => void;

111

override?: boolean;

112

children: React.ReactNode;

113

}

114

115

const RecoilRoot: React.FC<RecoilRootProps>;

116

```

117

118

[Root Provider](./root-provider.md)

119

120

### State Definition

121

122

Core functions for defining atoms and selectors that form the state graph.

123

124

```typescript { .api }

125

interface AtomOptions<T> {

126

key: string;

127

default?: T | RecoilValue<T> | Promise<T> | Loadable<T> | WrappedValue<T>;

128

effects?: ReadonlyArray<AtomEffect<T>>;

129

dangerouslyAllowMutability?: boolean;

130

}

131

132

function atom<T>(options: AtomOptions<T>): RecoilState<T>;

133

134

interface ReadOnlySelectorOptions<T> {

135

key: string;

136

get: (opts: { get: GetRecoilValue; getCallback: GetCallback }) =>

137

T | RecoilValue<T> | Promise<T> | Loadable<T> | WrappedValue<T>;

138

cachePolicy_UNSTABLE?: CachePolicyWithoutEquality;

139

dangerouslyAllowMutability?: boolean;

140

}

141

142

interface ReadWriteSelectorOptions<T> extends ReadOnlySelectorOptions<T> {

143

set: (opts: {

144

set: SetRecoilState;

145

get: GetRecoilValue;

146

reset: ResetRecoilState;

147

}, newValue: T | DefaultValue) => void;

148

}

149

150

function selector<T>(options: ReadWriteSelectorOptions<T>): RecoilState<T>;

151

function selector<T>(options: ReadOnlySelectorOptions<T>): RecoilValueReadOnly<T>;

152

```

153

154

[State Definition](./state-definition.md)

155

156

### Core Hooks

157

158

Essential React hooks for reading and writing Recoil state with automatic subscriptions.

159

160

```typescript { .api }

161

function useRecoilValue<T>(recoilValue: RecoilValue<T>): T;

162

function useRecoilState<T>(recoilState: RecoilState<T>): [T, SetterOrUpdater<T>];

163

function useSetRecoilState<T>(recoilState: RecoilState<T>): SetterOrUpdater<T>;

164

function useResetRecoilState(recoilState: RecoilState<any>): () => void;

165

function useRecoilValueLoadable<T>(recoilValue: RecoilValue<T>): Loadable<T>;

166

function useRecoilStateLoadable<T>(recoilState: RecoilState<T>): [Loadable<T>, SetterOrUpdater<T>];

167

```

168

169

[Core Hooks](./core-hooks.md)

170

171

### Family Patterns

172

173

Functions for creating parameterized atoms and selectors that are memoized by parameter.

174

175

```typescript { .api }

176

function atomFamily<T, P extends SerializableParam>(

177

options: AtomFamilyOptions<T, P>

178

): (param: P) => RecoilState<T>;

179

180

function selectorFamily<T, P extends SerializableParam>(

181

options: ReadWriteSelectorFamilyOptions<T, P>

182

): (param: P) => RecoilState<T>;

183

184

function selectorFamily<T, P extends SerializableParam>(

185

options: ReadOnlySelectorFamilyOptions<T, P>

186

): (param: P) => RecoilValueReadOnly<T>;

187

```

188

189

[Family Patterns](./family-patterns.md)

190

191

### Concurrency Helpers

192

193

Utilities for coordinating multiple async operations and handling loading states.

194

195

```typescript { .api }

196

function noWait<T>(state: RecoilValue<T>): RecoilValueReadOnly<Loadable<T>>;

197

function waitForAll<T extends Array<RecoilValue<any>>>(

198

param: T

199

): RecoilValueReadOnly<UnwrapRecoilValues<T>>;

200

function waitForNone<T extends Array<RecoilValue<any>>>(

201

param: T

202

): RecoilValueReadOnly<UnwrapRecoilValueLoadables<T>>;

203

```

204

205

[Concurrency Helpers](./concurrency-helpers.md)

206

207

### Advanced Hooks

208

209

Powerful hooks for complex operations including callbacks, transactions, and state introspection.

210

211

```typescript { .api }

212

function useRecoilCallback<Args extends ReadonlyArray<unknown>, Return>(

213

fn: (interface: CallbackInterface) => (...args: Args) => Return,

214

deps?: ReadonlyArray<unknown>

215

): (...args: Args) => Return;

216

217

function useRecoilSnapshot(): Snapshot;

218

function useGotoRecoilSnapshot(): (snapshot: Snapshot) => void;

219

```

220

221

[Advanced Hooks](./advanced-hooks.md)

222

223

### Loadable System

224

225

System for handling async state with loading, error, and success states.

226

227

```typescript { .api }

228

type Loadable<T> = ValueLoadable<T> | LoadingLoadable<T> | ErrorLoadable<T>;

229

230

interface ValueLoadable<T> {

231

state: 'hasValue';

232

contents: T;

233

getValue(): T;

234

valueOrThrow(): T;

235

}

236

237

namespace RecoilLoadable {

238

function of<T>(x: T | Promise<T> | Loadable<T>): Loadable<T>;

239

function error(x: any): ErrorLoadable<any>;

240

function loading(): LoadingLoadable<any>;

241

}

242

```

243

244

[Loadable System](./loadable-system.md)

245

246

### Memory Management

247

248

Tools for managing memory usage and preventing unwanted garbage collection of state.

249

250

```typescript { .api }

251

function useRetain(

252

toRetain: RecoilValue<any> | RetentionZone | Array<RecoilValue<any> | RetentionZone>

253

): void;

254

255

function retentionZone(): RetentionZone;

256

```

257

258

[Memory Management](./memory-management.md)

259

260

## Core Types

261

262

```typescript { .api }

263

// Base types

264

type NodeKey = string;

265

type SerializableParam =

266

| undefined | null | boolean | number | symbol | string

267

| ReadonlyArray<SerializableParam>

268

| ReadonlySet<SerializableParam>

269

| Readonly<{[key: string]: SerializableParam}>;

270

271

// ID types

272

interface StoreID {

273

readonly [StoreID_OPAQUE]: true;

274

}

275

276

interface SnapshotID {

277

readonly [SnapshotID_OPAQUE]: true;

278

}

279

280

// Snapshot types

281

class Snapshot {

282

getID(): SnapshotID;

283

getLoadable<T>(recoilValue: RecoilValue<T>): Loadable<T>;

284

getPromise<T>(recoilValue: RecoilValue<T>): Promise<T>;

285

getNodes_UNSTABLE(opts?: { isModified?: boolean; isInitialized?: boolean }): Iterable<RecoilValue<unknown>>;

286

getInfo_UNSTABLE<T>(recoilValue: RecoilValue<T>): RecoilStateInfo<T>;

287

map(cb: (mutableSnapshot: MutableSnapshot) => void): Snapshot;

288

asyncMap(cb: (mutableSnapshot: MutableSnapshot) => Promise<void>): Promise<Snapshot>;

289

retain(): () => void;

290

isRetained(): boolean;

291

}

292

293

class MutableSnapshot extends Snapshot {

294

set: SetRecoilState;

295

reset: ResetRecoilState;

296

}

297

298

// State info for debugging

299

interface RecoilStateInfo<T> {

300

loadable?: Loadable<T>;

301

isActive: boolean;

302

isSet: boolean;

303

isModified: boolean;

304

type: 'atom' | 'selector';

305

deps: Iterable<RecoilValue<T>>;

306

subscribers: {

307

nodes: Iterable<RecoilValue<T>>;

308

components: Iterable<ComponentInfo>;

309

};

310

}

311

312

interface ComponentInfo {

313

name: string;

314

}

315

316

// State types

317

class RecoilState<T> {

318

key: NodeKey;

319

toJSON(): {key: string};

320

}

321

322

class RecoilValueReadOnly<T> {

323

key: NodeKey;

324

toJSON(): {key: string};

325

}

326

327

type RecoilValue<T> = RecoilValueReadOnly<T> | RecoilState<T>;

328

329

// Special values

330

class DefaultValue {

331

private __tag: 'DefaultValue';

332

}

333

334

interface WrappedValue<T> {

335

readonly [WrappedValue_OPAQUE]: true;

336

}

337

338

// Function types

339

type SetterOrUpdater<T> = (valOrUpdater: ((currVal: T) => T) | T) => void;

340

type GetRecoilValue = <T>(recoilVal: RecoilValue<T>) => T;

341

type SetRecoilState = <T>(

342

recoilVal: RecoilState<T>,

343

newVal: T | DefaultValue | ((prevValue: T) => T | DefaultValue)

344

) => void;

345

type ResetRecoilState = (recoilVal: RecoilState<any>) => void;

346

type GetCallback = <Args extends ReadonlyArray<unknown>, Return>(

347

fn: (interface: SelectorCallbackInterface) => (...args: Args) => Return

348

) => (...args: Args) => Return;

349

350

// Selector callback interface

351

interface SelectorCallbackInterface extends CallbackInterface {

352

node: RecoilState<unknown>;

353

}

354

355

// Utility function

356

function isRecoilValue(val: unknown): val is RecoilValue<any>;

357

```