Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

296
Visualizações
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

about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda