But what is a Constructor?

In class-based_object-oriented programming, a constructor (abbreviation: ctor) is a special type of subroutine called to create an object. It prepares the new object for use, often accepting arguments that the constructor uses to set required member variables. ~ wiki link

So, in simple words with a Constructor we initialize the state of our component, and someone could say that “Function components don’t need a constructor. You can initialise the state in the useState call.”

The problem here is that Function components are… functions. They run whenever you call them. Just like that. This means that we don’t have life-cycles, which also means that we don’t have a place in which we can actually initialize our component with a code that runs only once before the component is rendered for the first time.

A real life example of the problem.

In the following example, we have a modal with an inner form. The performance field has a validation that is in sync with the discipline. Since this form is for editing and creating, we need to know with what validation we want to initialize the form. To achieve it, we pass the validation from the parent to the component via props and handle the validation with a Hook

Image for post

What we also want is to set the field values only when the component is initialised.

Image for post

We have the problem that each time we call the onFocusPerformance() the state is changing due to setPerformanceValidation() which leads to rerun the code block inside the red box and reset the values in the form again._

#react #react-hook #programming #javascript #developer

Use Constructor in React Functional Component with Custom Hooks
18.40 GEEK