reactjs / reactjs/react.dev

Document useDispatcher pattern

Open
#1,652 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
JavaScript
Stars
11.8k
Forks
7.9k
Avg merge
1d 11h
Merged PRs (30d)
11

Description

To mimic (easily testable) behaviour similar to redux thunk, a pattern such as useDispatcher can be used:

import React, { useReducer } from "react";
import ReactDOM from "react-dom";

import "./styles.css";

function App(props) {
  var { state, click } = useStore();

  return (
    <div>
      <h1>State: {state}</h1>
      <button onClick={click}>Increment</button>
    </div>
  );
}

function useStore(props) {
  var [ state, dispatch ] = useReducer(reducer, []);
  var { click } = useDispatcher(dispatch, props);

  return {
    state,
    click
  };
}

function useDispatcher(dispatch, props) {
  function click() {
    dispatch({ type: 'click' });
    setTimeout(() => afterclick(), 2000);
  }

  function afterclick() {
    dispatch({ type: 'afterclick' });
  }

  return { click };
}

function reducer(state, { type, dispatch }) {
  switch (type) {
    case "click":
      return [...state, "click wait 2s..."];
    case "afterclick":
      return [...state, "....after"];
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Documenting this pattern may also help to ensure this is an optimised approach, or whether another solution is preferable.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the useDispatcher example in the issue and inspect the React documentation structure to determine where this pattern could be documented. Compare it with redux-thunk-like behavior and decide whether the pattern is optimized or whether another solution is preferable; done means the documentation clearly explains the recommendation.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript, react
Domain
documentation
Issue type
Documentation
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.