State management

It's possible to use any state management library with Fusion.js. Below we provide a guide for using Redux, a popular state management library within the React community.

Using Redux

Redux is a state management library for web applications and works especially well with React. Fusion.js provides Redux integrations for its RPC plugins, and there are also open source developer tools available.


Where to put reducers

We recommend exporting a root reducer from src/redux.js:

export default {
  reducer: myReducer,
};

For example, given a state tree {count: 0} that responds to an action {type: 'INCREMENT'}, you would export this:

export default {
  reducer: (state, action) => ({
    count: state.count + (action.type === 'INCREMENT' ? 1 : 0),
  }),
};

Note: Unlike the example above, you should typically refactor a root reducer so that each key in the state object is handled by its own reducer. See combineReducers.

The Fusion.js fusion-plugin-react-redux plugin will set up a provider for you so you don't need to manually wrap your React tree with a provider.

Use connect from react-redux to expose the Redux state to React props:

// src/components/root.js
import {connect} from 'react-redux';

const hoc = connect(
  ({count}) => ({count}), // copies state.count into props.count
  dispatch => ({
    // defines that props.increment dispatches a `INCREMENT` action
    increment() {
      dispatch({type: 'INCREMENT'});
    },
  })
);

const Component = ({count, increment}) => (
  <button onClick={increment}>{count}</button>
);

export default hoc(Component);

To see how to integrate Redux with RPC calls, refer to the fetching data section.


Where to put enhancers

If you need to add enhancers or middlewares, export them like this:

export default {
  reducer,
  enhancer: myEnhancer,
};