Search code examples
reduxreact-nativeredux-loop

What is redux-loop and How can we use it in react native


What is redux-loop and what is the main purpose of using it in a React Native Application?


Solution

  • Redux Loop is a library that lets you run side effects from your reducers in a pure and testable way by porting the elm architecture to redux. It serves a similar purpose as redux-thunk and redux-saga.

    Here's an example where you can trigger a fetch and describe how to handle success and failure, all from your reducer.

    //reducer.js
    import { loop, Cmd } from 'redux-loop';
    
    const initialState = {
      loading: false,
      data: null,
      error: null
    }
    
    function reducer(state = initialState, action){
      if(action.type === 'pageLoaded'){
        const newState = {...state, loading: true};
        const cmd = Cmd.run(fetchData, {
          successActionCreator: dataLoaded,
          failActionCreator: dataLoadFailed,
          args: [action.itemId]
        });
        return loop(newState, cmd);
      }
      else if(action.type === 'dataLoaded'){
        return {
          ...state,
          loading: false,
          data: action.data,
          error: null
        };
      }
      else if(action.type === 'dataLoadFailed'){
        return {
          loading: false,
          error: action.error
        };
      }
      return state;
    }
    
    export default reducer;
    

    Notice that fetchData is never actually called from your reducer, so it is still a pure function that just returns data and is easily testable.

    You would use redux-loop it in a react-native application for the same reason that you would use it in a regular react application with redux, which is that redux by itself does not provide a way to directly run side effects from redux code. Instead it let you decide for yourself how you want to do that by allowing you to write middleware and store enhancers for redux, which redux-loop is.

    You can read more at https://redux-loop.js.org/

    Note: I maintain redux-loop