Store.js:
import {useReducer} from "react";
import {ACTION_TYPES} from "./storeActionTypes";
export const INITIAL_STATE = {
counter: 0,
};
export const storeReducer = (state, action) => {
switch (action.type) {
case ACTION_TYPES.INCREASE_COUNTER_BY_1:
return {
...state,
counter: state.counter + 1,
};
default:
return state;
}
};
const Store = () => {
const [state, dispatch] = useReducer(storeReducer, INITIAL_STATE);
return [state, dispatch];
};
export default Store;
AnyComponent.js
import React from "react";
import Store from "../store/Store";
const AnyComponent = () => {
const [store, dispatch] = Store();
const handleInceaseByOne = (e) => {
e.preventDefault();
dispatch({type: "INCREASE_COUNTER_BY_1"});
};
return (
<div>
<button onClick={(e) => handleInceaseByOne(e)}>Submit</button>
<span>counter from AnyComponent.js:{store.counter}</span>
</div>
);
};
export default AnyComponent;
OtherComponent.js
import React from "react";
import Store from "../store/Store";
const OtherComponent.js = () => {
const [store, dispatch] = Store();
return (
<div>
<span>counter from OtherComponent.js:{store.counter}</span>
</div>
);
};
export default OtherComponent.js;
So basically like in Redux, create a one Store where you store everything. In AnyComponent.js we have button who increase counter by 1 so we can see that value of store.counter in AnyComponent.js and OtherComponent.js.
Please anyone tell me if anything is wrong with this code?
Will try to upload this to GitHub later.
I looked in web and did not found anything what is similar to this so please let me know what you think.