How do I use stateful components with redux? How do I use stateful components with redux? reactjs reactjs

How do I use stateful components with redux?


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.


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.


Remember: There is no magic to redux; it's just a wrapper/container that is setting the props for you.

You can even use shouldComponentUpdate to manage how changing your stateful component's props should trigger the rendering.

Or leverging on connect's

areStatesEqualareStatePropsEqualareOwnPropsEqualareMergedPropsEqual

for greater control

related: https://stackoverflow.com/questions/58027300/what-is-the-main-difference-between-using-react-redux-hooks-and-react-redux-conn#:~:text=connect%20can%20be%20used%20with,used%20with%20function%20components%20only.&text=Using%20hooks%20is%20simpler.,disposal%20in%20comparison%20with%20connect%20.