@redneckz/react-dispatcher

React global action bus

Usage no npm install needed!

<script type="module">
  import redneckzReactDispatcher from 'https://cdn.skypack.dev/@redneckz/react-dispatcher';
</script>

README

react-dispatcher

TODO

NPM Version Build Status Coverage Status Bundle size

Installation

npm install --save @redneckz/react-dispatcher

How-to

import React from 'react';
import { useDispatcher } from '@redneckz/react-dispatcher';

const initialState = { count: 1000 };

/**
 * Local store. No need in "Lifting state up"
 */
function reducer(state, { type }) {
  switch (type) {
    case 'INC':
      return { count: state.count + 1 };
    case 'DEC':
      return { count: state.count - 1 };
    default:
      return state;
  }
}

export function Counter() {
  const [state, dispatch] = React.useReducer(reducer, initialState);
  const dispatcher = useDispatcher(state, dispatch);
  return (
    <button onClick={() => dispatcher({ type: 'INC' })}>{state.count}</button>
  );
}
import { useDispatcher } from '@redneckz/react-dispatcher';

/**
 * Some container far away from counter
 * and loosely coupled with containers
 * that support pattern { type: "dec" }
 */
export function Dec() {
  const dispatcher = useDispatcher();
  return <button onClick={() => dispatcher({ type: 'DEC' })}>-</button>;
}
import logger from 'redux-logger';
import thunk from 'redux-thunk';
import { useDispatcher, applyMiddleware } from '@redneckz/react-dispatcher';

/**
 * Produces new hook useDispatcher
 */
export default applyMiddleware(
  logger,
  thunk,
)(useDispatcher);

License

MIT