Ability to call setState in the constructor
See original GitHub issueA design question raised in another bug: https://github.com/facebook/react/issues/5313#issuecomment-152668532
What is the ideal behavior? Why don’t we support setState()
in the constructor? It seems better than having people manually add this.state = {...}
in the constructor, since the current method encourages the imperative pattern that can’t be used elsewhere in the component. cc @sebmarkbage for an answer.
Issue Analytics
- State:
- Created 8 years ago
- Reactions:2
- Comments:19 (13 by maintainers)
Top Results From Across the Web
React.Component
You may call setState() immediately in componentDidMount() . It will trigger an extra rendering, but it will happen before the browser updates the...
Read more >What will happen if you use `setState()` in constructor? - JS IQ
When you use setState() , then apart from assigning to the object state React also re-renders the component and all its children. You...
Read more >ReactJS setState() - GeeksforGeeks
setState is asynchronous call means if synchronous call get called it may not get updated at right time like to know current value...
Read more >Understanding React Component Constructor - KnowledgeHut
Never Call setState() Inside constructor() ... The constructor is the ideal place to set up your component's initial state. Instead of using ...
Read more >Understanding Constructors with React Components
You would lose the ability to run setState() later on and update the property. Instead of assigning the property directly to the state,...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Even componentWillMount is an anti-pattern. Another scenario is callbacks to a parent in componentWillMount. Where it may reach into a ref before the ref is uninitialized. It causes all kinds of strange artifacts.
Better to just move it to didMount.
Side-effects that change state due to a component being rendered is even more of an anti-pattern and may break scheduling etc.
Just talked with Sebastian, and we agreed that this is probably a pattern that we will never want to support. In most cases, calling
setState
in the constructor is an anti-pattern. The intended “story” for the future is to use property initializers once they land in ES7-ish, and then thethis.state = {...}
will go away.I’ll leave this issue open for another day or two in case people want to continue the discussion.