react-context-toolkit
Toolkit for React Context API - heavily inspired by @reduxjs/toolkit and react-redux. Written in TypeScript.
- It uses the React Context API instead of Redux for managing state under the hood.
- Depends on
use-context-selector
to prevent unneccesary rerenders. (https://github.com/reactjs/rfcs/pull/119)
Motivation
I really like the combination of react-redux and @reduxjs/toolkit. React-Redux won't work for me due to this issue:
The context API in React doesn't suffer from the same problem, so I decided to make this feel more like I'm using Redux.
API
createStore([...slices])
:
const StateProvider useSelector useDispatch Store initialState rootReducer =
returned object | description |
---|---|
StateProvider |
The context provider (React Element) that provides the store to all its children |
useSelector(selector) |
Hook that selects from the global store (and only rerenders if the selected state has changed) |
useDispatch() |
Hook that returns a dispatch function, just like the one in React-Redux |
Store |
In case you need direct access to the React Context object |
initialState |
The complete initial state. The slice names are keys, under which each slice has its own initialState |
rootReducer(state, action) |
The reducer that takes in the combined state, an action, and produces a new combined state |
createSlice()
: This is exported directly from @reduxjs/toolkit
. API DOCS HERE
Getting Started
Installation
# Using npm npm install --save react-context-toolkit # using yarn yarn add react-context-toolkit
Example
Also, check out the test folder for another example.
Wrapping the application in a provider
// ./src/index.tsx // Wrap your app in the state provider like this:ReactDOM.render , document.getElementById'root'
The App component
Notice that it doesn't need to know anything about the store
// src/App.tsx // Note that the App component doesn't need to know anything about the store!
Creating the store
// src/app/store.ts // In case you need direct access to the type of the combined state
Creating a slice (similar to how it is done in @reduxjs/toolkit)
// src/features/component1/componentSlice1.ts // ^ You can also import these from '@reduxjs/toolkit'
How state can be used and updated from a component
// src/features/component1/Component1.tsx
For more examples, see the test folder on GitHub
Roadmap
- Ability to add your own middleware/docs
- Redux-thunk support/docs
- Redux-saga support/docs
- Persistence support/docs (using localStorage) -> requiring serializable state
- Reselect support/docs (for computationally intensive selects)