react-reducer-provider.github.io

Asynchronous/Synchronous React Centralized State

Follow me on GitHub

React Reducer Provider with Injection and Typescript typings

1 . Add react-reducer-provider (and prerequisite) to package.json:

  ..
  "dependencies": {
    "react": "^16.8.0"
    "react-reducer-provider": "5.0.0",
    ..

2 . Create the Reducer Provider:

  • Define the State.
  • Define the Reducer.

SomeReducerProvider.jsx:

import React from 'react'
import { SyncReducerProvider } from 'react-reducer-provider'

const initialState = 0

function reduce(prevState, action) {
  switch (action) {
    case 'ACTION1':
      return prevState + 1
    case 'ACTION2':
      return prevState - 1
    default:
      return prevState
  }
}

function SomeReducerProvider({ children }) {
  return (
    <SyncReducerProvider
      id='someNamedReducer'
      reducer={reduce}
      initialState={initialState}
    >
      {children}
    </SyncReducerProvider>
  )
}

export {
  SomeReducerProvider
}

3 . Define some Components:

SomeComponent1.jsx:

import React from 'react'

export default function SomeComponent1({dispatch}) {
  return (
    <button onClick={() => dispatch('ACTION1')}>
      Go up!
    </button>
  )
}

SomeComponent2.jsx:

import React from 'react'

export default function SomeComponent2({dispatch}) {
  return (
    <button onClick={() => dispatch('ACTION2')}>
      Go down!
    </button>
  )
}

SomeComponentN.jsx:

import React from 'react'

export default function SomeComponentN({currentState}) {
  return (
    <div>
      Current:{currentState}
    </div>
  )
}

4 . Create the bridge between the Reducer Provider and the Components:

SomeContainer.jsx:

import SomeComponent1 from './path/to/SomeComponent1'
import SomeComponent2 from './path/to/SomeComponent2'
import SomeComponentN from './path/to/SomeComponentN'
import { useReducer } from 'react-reducer-provider'
import React from 'react'

export default function SomeContainer() {
  const [ state, dispatch ] = useReducer('someNamedReducer')
  return (
    <div>
      <SomeComponent1 dispatch={dispatch}/>
      <SomeComponent2 dispatch={dispatch}/>
      <SomeComponentN currentState={state}/>
    </div>
  )
}

SomeMain.jsx:

import SomeContainer from './path/to/SomeContainer'
import { SomeReducerProvider } from '../path/to/SomeReducerProvider'
import React from 'react'

export default function SomeContainer() {
  return (
    <SomeReducerProvider>
      <SomeContainer />
    </SomeReducerProvider>
  )
}

This example can be checked on line at gmullerb-react-reducer-provider-with-injection codesandbox:
Edit gmullerb-react-reducer-provider-with-injection
with Flow typings.
with Typescript typings.

Main documentation

Back to homepage