Ben Aston Ben Aston - 1 year ago 65
React JSX Question

How do I decide whether a component should have its own reducer function?

How do I decide whether a component should have its own reducer function, or delegate to an ancestor component?

For example:

I have a

HomePage
component with a reducer function that is registered with the store when the page is visited via the router.

The
HomePage
component contains within it an instance of a
Grid
component.

<div>
<Grid contents={contents} />
</div>


The
Grid
component needs to recalculate the number columns it uses when the viewport is resized, so I add an action associated with the
Grid
named
UPDATE_COLUMN_COUNT
.

A call to dispatch this action is bound to the
window
resize
event in the
onComponentDidMount
of
Grid
.

For
Grid
, where should I register its reducer with the store?

Should I register it manually in the router (together with the existing registration of the
HomePage
reducer)?

Should I somehow combine the reducer for
HomePage
with the reducer for
Grid
?

Or should I respond to the
UPDATE_COLUMN_COUNT
action in the
HomePage
reducer and not have a reducer for this component?

Answer Source

Personally, I would use the local component state for this rather than storing in my Redux store. This is a purely display concern that will not affect any other component so I don't want to over complicate my code.

If this number of columns could be used throughout the application by different components then you might want to put it in the Redux state.

Generally, the application state should be loosely coupled from the components you use, i.e. you don't try to map components to reducers. Instead, you create the relevant application state by composing your reducers and select the relevant parts for each component.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download