In my React/Redux app I am often facing with the problem of implementing components with state which should be used throughout the app. Let's take simple popup component as an example with open/close state which can be reused in any page. Here is two possible approaches I found:
Use setState
and "local" reducer (I use recompose.withReducer which is just syntax sugar for React's native setState
) to manage its state. It looks easy and reusable until you need change the component's state in the other part of your page (close popup in out case). And you cannot just call some redux action to change the state.
Keep the component's state in the Redux store. With such approach we can call closePopupAction({ id })
in any place of the components tree to change it's state.` But we need somehow put its reducer (which i want to keep in the popup's folder) to the root reducer when the component is mounted and delete it when the component is unmounted. Plus we can have multiples popups in the page and each of them have its own state.
Did anybody face with a similar problem ?
In React, a reusable component is a piece of UI that can be used in various parts of an application to build more than one UI instance. For instance, we can have a Button component that displays different texts on different pages.
Some users prefer to keep every single piece of data in Redux, to maintain a fully serializable and controlled version of their application at all times. Others prefer to keep non-critical or UI state, such as “is this dropdown currently open”, inside a component's internal state. Using local component state is fine.
Containers are the primary components and the entry point from which we call child or generic components. Basically, container components are called smart components because each container component is connected to Redux and consumes the global data coming from the store.
First we have to import the component into where we want to reuse it, as you can see in the first line of the above code where we have our import statement. Second, because we passed in name and imageUrl as props in the author component earlier, the author component expects the same data to be passed into it at first.
I think you should keep state of component in redux. You can create reducer for this component and use combineReducers function in this way:
rootReducer = combineReducers({
moduleA: combineReducers({
popupA: popupReducer("id1"),
popupB: popupReducer("id2")
}),
moduleB: combineReducers({
popupA: popupReducer("id3")
})
})
});
then when you call closePopupAction("id1") reducer can check id and change proper part of state.
PS: Id should be provided in better way :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With