immer-wieder
is an api-compatible wrap around Reacts context, behaving the same way with the distinction that you can
- provide actions
- mutate state directly instead of writing reducers (it's using immer)
- optionally select state, so that components only render when the state they subscribe to changes
If you look at the code it should become clear that it lets React do all the work in order to create as little surface for maintenance and bugs as possible.
Install
npm install immer-wieder
Import
import createContext from 'immer-wieder'
Create context
const Provider Consumer =
Provide once, then consume, anywhere within the providers tree
const App = // Provide state, everything withing can have selective access to it <Provider> <Consumer => ids </Consumer> </Provider> const EditDetails = id // Select is optional, if present the component renders only when the state you select changes // Actions can be fetched right from the store <Consumer => name changeName <div> <h1>name</h1> <input = = /> </div> </Consumer>
void
Inline mutations using Draft mutations usually warrant a code block, since a return denotes a overwrite in immer. Sometimes that can stretch code a little more than you might be comfortable with. In such cases you can use javascripts void
operator, which evaluates expressions and returns undefined
.
// Single mutation // Multiple mutations
What about HOCs?
Sometimes you need to access state in lifecycles or maybe you just don't like render props at all.
import createContext from 'immer-wieder' const Provider hoc = @ { return <div>thispropsitem</div> } const App = <Provider> <Item = /> </Provider>
Contributions
All my open source projects are done in my free time, if you like any of them, consider helping out, all contributions are welcome as well as donations, for instance through Patreon.