I’m looking to gather a set of guidelines one should keep in mind while building my React components; what are the times when I should be making it a controlled component, and why?
To ask a question further; how should I be managing controlled components, when using something like Redux; would component level state be considered a bad practice?
Controlled components are primarily related to forms, since input elements normally store their own value internally and allow you to ask for that value later. By always forcing the input to have a value you specify, and handling the change events yourself with updates to your state, dealing with inputs becomes more predictable.
As for Redux, it's entirely fine to use component-level state wherever you feel it's necessary. For example, having an input that's connected to Redux and dispatching an action on every keystroke may be overkill, so tracking the input's value in component state and only dispatching the action on form submission may simplify things.
FYI, I keep a big list of links to high-quality articles on React, Redux, and related topics, at https://github.com/markerikson/react-redux-links . As part of that list, I have a page of articles talking about React and Forms that you may find useful, including a number of articles on controlled inputs.
You may also want to refer to the Redux FAQ question on Redux state vs React component state.
Mark Erikson
I write code :)
The question is more like : this.props vs this.state
Controlled components (or stateless components) :
Controlled components are designed to be use by an other components (also called 'containers') that manage props for them. So :
Uncontrolled components (or statefull components) :
Uncontrolled components are designed to be used everywhere.
Pros :
Cons :
Conclusion :
Both of them can consuming your time in a heavy way if you choose the wrong 'paradigm'. Ask you everytime the question : If you do not have to share the component's state with an other component, go to Uncontrolled component and let it manage its own state :
If you have to know the state of the component, you have to control it ! Go to Controlled component :
Do not forget this : You can mix them together, but each time you will use an Uncontrolled Component, its a part of your app you cannot predict and test. So the question is : Do you care about testing your component ?