Zero-cost bindings to Facebook's Recoil library
⚠️ These bindings are still in experimental stages, use with caution
Run the following command:
$ yarn add recoil rescript-recoil
Then add rescript-recoil
to your bsconfig.json
's dependencies:
{
"bs-dependencies": [
+ "rescript-recoil"
]
}
let textState = Recoil.atom({
key: "textState",
default: "",
})
A nice feature the OCaml type-system enables is the ability to differenciate Recoil values between the ones that can only read state with the ones that can write state. This way, you can't use hooks with write capabilities with a read-only value.
let textStateSize = Recoil.selector({
key: "textStateSize",
get: ({get}) => {
let textState = get(textState)
Js.String.length(textState)
},
})
let textStateSize = Recoil.selectorWithWrite({
key: "textStateSize",
get: ({get}) => {
let textState = get(textState);
Js.String.length(textState);
},
set: ({set}, newSize) => {
let currentTextState = get(textState);
set(textState, currentTextState->Js.String.slice(~from=0, ~to_=newSize));
}
});
let user = Recoil.asyncSelector({
key: "user",
get: ({get}) => {
fetchUser(get(currentUserId))
},
})
useRecoilState
let (state, setState) = Recoil.useRecoilState(textState);
state // read
setState(textState => newTextState) // write
useRecoilValue
let state = Recoil.useRecoilValue(textState)
state // read
useSetRecoilState
let setState = Recoil.useSetRecoilState(textState)
setState(textState => newTextState) // write
useResetRecoilState
let reset = Recoil.useResetRecoilState(textState)
reset() // write
useRecoilCallback
useRecoilCallback(...)
useRecoilCallback0(...)
useRecoilCallback1(..., [|dep|])
useRecoilCallback2(..., (dep1, dep2))
(goes from 2 to 5)let onClick = Recoil.useRecoilCallback(({snapshot: {getPromise}}, event) => {
let _ = getPromise(myAtom)
|> Js.Promise.then_(value => {
Js.log(value)
Js.Promise.resolve()
})
})
<button onClick={onClick}>
{"Click me"->React.string}
</button>
useRecoilValueLoadable
let loadable = Recoil.useRecoilValueLoadable(textState)
Js.log(loadable->Recoil.Loadable.state)
Js.log(loadable->Recoil.Loadable.getValue)
The Recoil Basic Tutorial has been made in ReasonReact: check the source!
You can run it using:
$ yarn examples
and going to http://localhost:8000/TodoList.html
type t = {
id: string,
value: string,
isCompleted: bool,
}
// For atoms
let todoItemFamily = Recoil.atomFamily({
key: "todo",
default: param => {
id: param,
value: "",
isCompleted: false,
},
})
// For selectors
let todoItemLengthFamily = Recoil.selectorFamily({
key: "todo",
// The `Fn` wrapper is needed here so that BuckleScript
// outputs the correct value
get: param => Fn(({get}) => {
get(todoItemFamily(param)).value->Js.String2.length
}),
})
And use it within a React component:
[@react.component]
let make = (~todoId) => {
let (todo, setTodo) = Recoil.useRecoilState(todoItemFamily(id))
// ...
<>
{todo.value->React.string}
</>
}