https://github.com/anber/recoil-context
A distributed context on top of Recoil
https://github.com/anber/recoil-context
Last synced: over 1 year ago
JSON representation
A distributed context on top of Recoil
- Host: GitHub
- URL: https://github.com/anber/recoil-context
- Owner: Anber
- License: mit
- Created: 2020-05-26T15:28:20.000Z (about 6 years ago)
- Default Branch: master
- Last Pushed: 2023-01-06T07:03:58.000Z (over 3 years ago)
- Last Synced: 2025-02-10T20:34:31.669Z (over 1 year ago)
- Language: TypeScript
- Size: 1.66 MB
- Stars: 2
- Watchers: 4
- Forks: 0
- Open Issues: 14
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# `recoil-context`: a distributed context on top of [Recoil](https://recoiljs.org)
## Installation
```
npm install --save recoil-context recoil
// or
yarn add recoil-context recoil
```
## Example
```typescript
// WizardContext.ts
import { createContext } from "recoil-context";
const { RecoilContext, useContextValue, useSetContextValue } = createContext({
paymentMethod: "card" as "card" | "paypal",
step: 1,
});
export { useContextValue, useSetContextValue };
export default RecoilContext;
```
```tsx
// Wizard.ts
import WizardContext, { useContextValue, useSetContextValue } from "./Wizard";
const Tab = ({ children, id }) => {
const setStep = useSetContextValue("step");
return setStep(id)}>{children};
};
const Tabs = () => {
const method = useContextValue("paymentMethod");
const step = useContextValue("step");
return (
1}>Payment details
2}>
{method === "card" ? "Card details" : "PayPal authorization"}
3}>Confirmation
)
};
const Panels = () => {
const method = useContextValue("paymentMethod");
const step = useContextValue("step");
if (step === 1) { /* … */ }
if (step === 2 && method === "card") { /* … */ }
if (step === 2 && method === "paypal") { /* … */ }
if (step === 3) { /* … */ }
}
const Wizard = () => {
return (
);
}
```
## API
`recoil-context` exports only one function:
##### `createContext(defaultValues: TValues): { RecoilContext, useContextValue, useSetContextValue }`.
It accepts an object with default values and creates a strictly typed context and pair of hooks for getting and setting values:
* `RecoilContext` is a container for your state and provides values for hooks. Default values can be fully or partially overridden with `initialValues` prop;
* `useContextValue(name: T): TValues[T]` returns current value from the context;
* `useSetContextValue(name: T): Dispatch>` returns a value setter for specified field.
## License
MIT