Skip to content

Instantly share code, notes, and snippets.

@DominikStyp
Created January 16, 2022 11:58
Show Gist options
  • Save DominikStyp/49bb3a3e62fd1da5f82c2fc89c6fbc85 to your computer and use it in GitHub Desktop.
Save DominikStyp/49bb3a3e62fd1da5f82c2fc89c6fbc85 to your computer and use it in GitHub Desktop.
React: custom redux-like store
import { initStore } from './store';
const configureCounterStore = () => {
const actions = {
COUNTER: (curState) => {
console.log(curState);
return { ...curState, counter: counter+1 };
}
}
initStore(actions, { counter: 0 });
};
export default configureCounterStore;
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import './index.css';
import App from './App';
import configureCounterStore from './hooks-store/counter-store';
configureCounterStore(); //setting default values for the counter store
ReactDOM.render(
<BrowserRouter>
<App />
</BrowserRouter>,
document.getElementById('root')
);
import { useStore } from './hooks-store/store';
const MyComponent = () => {
const dispatch = useStore(false)[1];
const updateCounter = () => {
dispatch('COUNTER');
};
return (
<div>
<button onClick={updateCounter}>Click Me</button>
</div>
);
}
export default MyComponent;
import { useState, useEffect } from 'react';
let globalState = {};
let listeners = [];
let actions = {};
export const useStore = (shouldListen = true) => {
const setState = useState(globalState)[1];
const dispatch = (actionIdentifier, payload) => {
const newState = actions[actionIdentifier](globalState, payload);
globalState = { ...globalState, ...newState };
for (const listener of listeners) {
listener(globalState);
}
};
useEffect(() => {
if (shouldListen) {
listeners.push(setState);
}
return () => {
if (shouldListen) {
listeners = listeners.filter(li => li !== setState);
}
};
}, [setState, shouldListen]);
return [globalState, dispatch];
};
export const initStore = (userActions, initialState) => {
if (initialState) {
globalState = { ...globalState, ...initialState };
}
actions = { ...actions, ...userActions };
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment