Search code examples
reactjsreduxreact-contextreact-state-management

can I use context API as almost another source of truth in a project that already has Redux?


I'm working on a project utilizes Redux for managing states of the app. As we know, in Redux there is a principle rule called having only one source of truth which simply means there is just a single JS value containing all of the existing states of the app, called store. So in this store we kind of reserve every states with a unique parameter. For Example in the mapStateToProps function:

const mapStateToProps = state => myInfo: state.users.myInfo

As you can see, in this case state.users is get reserved as an object in the state of the app. However in another part of the project I need to work with another API which its response contains an array with property of "users" (BTW it can not get changed, it should handle in Front-End). So I cannot use something like activeUsers: state.users in another component and get back an array of active users.

My question is can I use context API state manager for the new part of the project to handle this parameter duplication issue?


Solution

  • No matter how that second users property is called on the server, nothing stops you from giving it a name like redUnicorns or activeUsers - these are variable names that you as the programmer give to things. Just in your configureStore or combineReducers call, give the whole reducer a different name:

    const store = configureStore({
      users: usersReducers,
      greenPotatoes: myOtherUsersReducer
    })
    
    // data will be `store.greenPotatoes` now
    

    or if you are writing legacy redux with combineReducers (please read why RTK is Redux in that case and start using Redux Toolkit, which will reduce your code down to 1/4 of what it is now)

    const rootReducer = combineReducers({
      users: usersReducers,
      greenPotatoes: myOtherUsersReducer
    })
    

    Of course it is generally possible to use Context next to Redux, and that is perfectly viable in dependency injection scnearios, the question is "does it make sense" - and I have to say that in your case you just seem to be missing that you can call things however you like to call them in your end of the code - completely independently of which name they have somewhere else.