its-not-redux v0.4.2
its-not-redux
A very small flux-compatible library for React.js
Have you ever wanted to make a small React.js project, but got frustrated at how many times you needed to "lift up the state"? Did you ever wish you had a single global state store, but found the amount of boilerplate required for Redux apalling? Then this is the library for you!
Pros
- Easy to use, great for small projects
- Full flux compatability (at least the parts you actually need)
- Typescript compatable™
- Fully documented
- Only 35 lines of code (check it all out here)
- (The main features of Redux are not super hard to implement)
Cons
- Causes a full app re-render every time the state changes. (Don't use it for big projects!)
- Lacks features
- Is actually just a thin wrapper over the React Context and React Hooks API
Installation
$ npm install its-not-redux
Usage
Create your reducers and your actions following the flux pattern, just like you might for redux. Then create a store using createStore()
.
If you're not familiar with the flux pattern, read the Basic Redux Tutorial. Also make sure you are comfortable using React.js if you arent
// ----- store.jsx (or however you like to organize it) -----
import { createStore } from "its-not-redux";
// Actions
// You can implement your own action creators if you wish
export const INCREMENT = "INCREMENT";
export const DECREMENT = "DECREMENT";
// State
const initialState = {
counter: 0,
};
// Reducers
function reducer(state, action) {
switch (action.type) {
case INCREMENT:
return {
counter: state.counter + 1,
};
case DECREMENT:
return {
counter: state.counter - 1,
};
}
}
// Library magic ;)
const { StateProvider, useStore } = createStore(reducer, initialState);
export { StateProvider, useStore };
createStore()
returns a React Context Provider, and the function useStore()
, which can be used in the exact same ways as a state hook.
Wrap your main App
component with the StateProvider
, so that the store can be used everywhere in your app.
// ----- index.jsx -----
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import { StateProvider } from "./store";
ReactDOM.render(
<StateProvider>
<App>
</StateProvider>,
document.getElementByID("root")
);
And access your state from anywhere using the useStore()
function. Just like how you might use a state hook.
// ----- App.jsx (or any other component) -----
import React from "react";
import { INCREMENT, DECREMENT, useStore } from "./store";
function App() {
// Using the redux-like store
const [state, dispatch] = useStore();
return (
<div>
<span>Counter: {state.counter}</span>
<button onClick={() => dispatch({ type: INCREMENT })}>
Increment the counter
</button>
<button onClick={() => dispatch({ type: DECREMENT })}>
Decrement the counter
</button>
</div>
);
}
export default App;