61

I'm trying to build keyboard shortcut support into my React/Redux app in an idiomatic React/Redux way. The way I am planning to do this is to have the following action creator and associated action:

registerShortcut(keyCode, actionCreatorFuncReference)

The reducer would then update a registeredShortcuts object in the redux store with a mapping of keyCodes to actionCreatorFuncReferences. Then my root component would listen for keyup and see if there is an associated keyCode registered and if so, then dispatch the mapped action via the action creator function reference.

However, this would be the first time I am storing function references in my Redux store. To date, I've only had objects with keys with vanilla values (strings, ints, etc).

The Redux docs says:

You should do your best to keep the state serializable. Don’t put anything inside it that you can’t easily turn into JSON.

Does this suggest it's a bad idea to store such function references in my Redux store? If so, what is a better way to accomplish what I'm trying to do in React/Redux?

An alternative approach is just to store the mapping of keyCodes and function references in the root react component itself, but that didn't feel very Redux-like since now the application state is not in the Redux store.

1
  • 3
    I've been sort of wondering about this sort of thing myself. While Redux state definitely needs to be serializable, there ARE other things you might want to keep around at times (promises, etc). I just raised this question over in github.com/rackt/redux/issues/1385 - we'll see if anything comes up. Feb 10, 2016 at 22:18

3 Answers 3

50

No, you should not store function references in the redux store. They are not serializable, and as you mentioned state should be serializable at all times. The most redux-friendly approach I can think of is just to keep the map of hotkeys to their actionCreatorFuncNames.

7
  • That's an interesting idea. How would I then actually execute the function from the actionCreatorFuncNames string? Feb 10, 2016 at 20:36
  • 1
    I think that would depend on the details of your application. It would be easy to just import all of your actions onto a single actions object wherever you're handling these key events. The hard part is contextualizing the button press and calling actions[actionCreatorFuncNameA] with the proper arguments. On the other hand, if hotkeys are all toggles, then you don't need to call any arguments and the problem is solved. Does that make sense, or am I off base? Feb 10, 2016 at 22:28
  • 34
    It's fine to store functions in your store - as long as you are aware of the tradeoffs involved. From the FAQ: "If you are okay with things like persistence and time-travel debugging potentially not working as intended, then you are totally welcome to put non-serializable items into your Redux store." redux.js.org/docs/faq/…
    – seb
    Mar 7, 2017 at 18:14
  • 2
    Who says redux store should be serializable? Unless you do server rendering, I don't see value in avoiding it.
    – Ville
    Dec 3, 2018 at 21:49
  • 3
    Looks like Redux has changed its mind on the issue: redux.js.org/style-guide/… Non-serializable items are not recommended, except when they are intended to be intercepted by middleware. Apr 23, 2020 at 17:35
22

TL;DR: You don't. The store state must be serializable at all times (as Nathan answered). The Redux way is via enhancers, or the Redux-Observable way via dependencies.

NL;PR: Based on the Redux docs example, what you want is to pass the reference in your action(1), ignore it your reducer(2) and use it in your enhancer(3):

    //... in your action:
    const data={val:1}, ref=()=>{};
    const action = {type:'ACTION_WITH_REF', data, ref}; //(1)

    //... in your reducer:
       case 'ACTION_WITH_REF':
       return {...state, data: action.data}; //(2)

    //... and in your enhancer:
    import { createStore, applyMiddleware } from 'redux';
    import reducers from './reducers';
    export const myRefStore= {};
     
    function refHandler({ getState }) {
      return next => action => {
        switch(action.type){ 
           // this can be done more elegantly with a redux-observable
           case 'ACTION_WITH_REF':
             myRefStore.aRef = action.ref; // (3)
             break;
         }
        // be sure to maintain the chain of the store
        const returnValue = next(action);   
        // otherwise, your midddeware will break the store
        return returnValue;
      };
    } 

    const store = createStore(
      reducers,
      initialState,
      applyMiddleware(refHandler)
    );

Note: As far as there are no side-effects in your enhancers, you are good to go. Be aware that you could have obtained the refs directly in the reducers, but such an approach keeps the reference at the reducer-level and misses the point of combineReducers(). With an enhancer, you keep them all in one place(myRefStore).

One final observation is that a redux store is not an any-data store but a state store, thus why we need to handle functions and other non-state related stuff in enhancers. You can leverage the enhancer backbone to Redux-Observable and inject myRefStore via dependencies.

1
  • 2
    Your answer is really good and should be the accepted solution! I was able to store a function in a really complex structure thanks to your example ;) Apr 30, 2018 at 15:20
2

I'm new to redux, but the way I see it, you could pass the key code and an action type. Then a reducer could be listening for that action type and make changes accordingly.

Here is an example using the library Mousetrap:

// On your Container
function registerShortcut(element, dispatch, keyCode, actionType) {
  Mousetrap(element).bind(keyCode, function(e) {
    dispatch({
      type: actionType,
      payload: {
        keyCode: keyCode,
        event: e
      }
    });
  });
});

mapDispatchToProps = function(dispatch) {
  return {
    onMount: function(element) {
      registerShortcut(element, dispatch, ['command+f', 'ctrl+f'], 'OPEN_SEARCH');
    },
    onUnmount: function(element) {
      Mousetrap(element).unbind(['command+f', 'ctrl+f']);
    }
  };
};


// On your Component
componentDidMount() {
  onMount(ReactDOM.findDOMNode(this));
};

componentWillUnmount() {
  onUnmount(ReactDOM.findDOMNode(this));
};



// On your reducer
function reducer(oldState, action)  {
  if (action.type == 'OPEN_SEARCH') {
    //... make changes ...//
    return newState;
  }
  return oldState;
};

This way, keyboard shortcuts will dispatch an action. The reducer will make the changes necessary to the state. And finally, the application can re-render.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.