Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/sikanhe/reason-atomic
Dead simple shared state in Reason React with a redux-like interface.
https://github.com/sikanhe/reason-atomic
reason-react reasonml redux state-management
Last synced: 10 days ago
JSON representation
Dead simple shared state in Reason React with a redux-like interface.
- Host: GitHub
- URL: https://github.com/sikanhe/reason-atomic
- Owner: sikanhe
- License: mit
- Created: 2019-04-20T17:42:53.000Z (over 5 years ago)
- Default Branch: master
- Last Pushed: 2019-04-20T20:40:27.000Z (over 5 years ago)
- Last Synced: 2024-10-12T13:34:35.827Z (27 days ago)
- Topics: reason-react, reasonml, redux, state-management
- Language: OCaml
- Size: 7.81 KB
- Stars: 19
- Watchers: 2
- Forks: 2
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
- awesome-list - reason-atomic - like interface. | sikanhe | 19 | (OCaml)
README
# Atomic [![npm version](https://img.shields.io/npm/v/reason-atomic.svg)](https://www.npmjs.com/package/reason-atomic)
Dead simple shared state in Reason React with a redux-like interface.
# Installation
```bash
yarn add reason-atomic
```Then add `reason-atomic` to your `bs-dependencies` in `bsconfig.json`
```
{
...
"bs-dependencies": ["reason-atomic"]
}```
# Usage
Configure your state by creating a module with `state`, `getInitialState`, `action`, and `reducer`.
```reason
module Config = {
type state = {count: int};let getInitialState = () => {count: 0};
type action =
| Increment
| Decrement
| NoChange;let reducer = state =>
fun
| Increment => {count: state.count + 1}
| Decrement => {count: state.count - 1}
| NoChange => state;};
```Create a new state module with the config
```reason
module AppState = Atomic.Make(Config);
// module AppState2 = Atomic.Make(Config);
// module AppState3 = Atomic.Make(Config);// Create as many instances as you like..
```Access the state as a hook, and dispatch actions
```reason
[@react.component]
let make = () => {
let state = AppState.useState();
;
{React.string("global count: " ++ string_of_int(state.count))}
AppState.dispatch(Increment)}> {React.string("+")}
AppState.dispatch(Decrement)}> {React.string("-")}
};
```If you only care about a subset of the state, you can use `useMappedState`. This also means that
the component with the hook won't re-render unless the state it cares about changes - avoiding excessive re-rendering.```reason
[@react.component]
let make = () => {
let count = AppState.useMappedState(state => state.count);
;
{React.string("global count: " ++ string_of_int(count))}
};
```You can also use the render-props pattern to consume the state as well, using the `Consumer`
component and pass the `mapper` prop.```reason
[@react.component]
let make = () => {
state.count}>
{count => React.string("global count: " ++ string_of_int(count))}
;
};
```