Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use stateful components with redux?

Tags:

reactjs

redux

I am trying redux right now and very excited about ideas behind it, but first real task ruined the whole thing.

In Redux we should store immutable state and produce some reducers to transform it. It means that every state could be reproduced by given previous state and a list of actions fired.

But what if I need to store third-party/legacy stateful object? For example it may be something like gallery or websocket client. I assume that I'm able to use reducers to start/stop/manage it somehow, but the state I have no longer stateless and it not guaranteed to be repeatable with given list of reducers (websocket client may generate new session id or even be unable to maintain connection).

What is convenient way to solve these issues?

like image 407
Elessar.perm Avatar asked Aug 08 '16 16:08

Elessar.perm


2 Answers

As I see this, your problem boils down to: How do you mix Redux with stateful components (legacy/third party)?

You are right, Redux is better suited for controlled components, that is, components that are mostly stateless and are supposed to receive everything as props. Just keep in mind that having some state doesn't necessarily make the component unusable in Redux. Example: For an Autocomplete component, the "open" state (whether or not the dropdown is visible) doesn't necessarily has to be controlled by Redux. So, depending on the how the component is implemented, you're definitely having a hard time integrating it into Redux, or maybe not.

You have 2 options: You either refactor the problematic components so they're now controlled, or you don't keep their state on Redux (you're not required to). The answer will vary depending on the circumstances. There's not a globally accepted solution for your case, that I know of.

like image 186
André Pena Avatar answered Sep 29 '22 09:09

André Pena


Here's a nice explanation from the FAQ docs. In short:

Do I have to put all my state into Redux? Should I ever use React's setState()?

There is no “right” answer for this. 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. As a developer, it is your job to determine what kinds of state make up your application, and where each piece of state should live. Find a balance that works for you, and go with it.

There's a bunch more info there -- worth reading the whole thing.

like image 40
Hawkeye Parker Avatar answered Sep 29 '22 10:09

Hawkeye Parker