'How to write cutsom redux hooks replicating what redux does fundamentally?

Just stumbled upon the question of writing custom redux hooks. Here is a backbone of the App.js

import { Provider, useStore, useDispatch } from "./redux";
import reducers from "./reducers";
import "./styles.css";
import React} from "react";

function Hello() {
  const counter = useStore(store => store.counter);
  const dispatch = useDispatch();

  const increment = () => dispatch({ type: "INCREMENT" });

  const decrement = () => dispatch({ type: "DECREMENT" });

  return (
    <div>
      <h3>Counter: 0</h3>
      <button onClick={increment}>+ Increment</button>
      &nbsp;
      <button onClick={decrement}>- Decrement</button>
    </div>
  );
}
// <Provider reducers={reducers}>
export default function App() {
  return (
    <div className="App">
      <Provider reducers={reducers}>
        <Hello />
      </Provider>
    </div>
  );
}

The idea is to write implementations for useStore, useDispatch and Provider.

I got the idea that we should use context api and useReducer to have access to dispatch but then I got stuck.

I know Provider can something be like

const initialState = {};

const context = createContext(initialState);

export function Provider({ children, reducers }) {
  const [state, dispatch] = useReducer(reducers, initialState);
  // children need to have access to dispatch
  return (
    <context.Provider value={{ state, dispatch }}>{children}</context.Provider>
  );
}

And similarly we could have used useContext to have access to the value passed like

export function useStore(selector) {
  const { state} = useContext(context);
  return { state.selector};
}

/**
 * Returns the dispatch function
 */
export function useDispatch() {
  const { dispatch } = useContext(context);
  return { dispatch };
}

reducers file is also a part of the sandbox link given below. But I am stuck and cannot figure why it's not working. Please help and explain. Here is the work in progress sandbox https://codesandbox.io/s/redux-forked-tlb4hb?file=/src/redux.js



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source