DEV Community

Discussion on: Constructors in Functional Components With Hooks

Collapse
 
bytebodger profile image
Adam Nathaniel Davis

The easiest analogy is componentWillMount. Anything that anyone previously wanted to stuff in componentWillMount is a prime candidate to be put in the constructor. But don't take my word for it. This is directly from the React docs:

UNSAFE_componentWillMount() is invoked just before mounting occurs. It is called before render(), therefore calling setState() synchronously in this method will not trigger an extra rendering. Generally, we recommend using the constructor() instead for initializing state.

So if you were using old-skool React, you might've had a handful of components that used componentWillMount(). Then, that was deemed to be unsafe, and the maintainers themselves said, "Now you should move it to the constructor(). But with function-based components, there is no constructor.

Again, as I stated in the post, I'm not claiming that this is functionality that you'd need on all components. You won't even need it on most components. But the fact that we previously had componentWillMount() and constructor() signals that there are valid use-cases for it.