Shreyas Shreyas - 5 months ago 40
React JSX Question

What exactly is a Stateless Controlled Component in React

In an interview I was asked to create an autofill component with two conditions It should be a controlled component and it should be stateless.
But after going through the react docs, what I understood was, a component is a controlled component only when its input has a single source of truth which is in the state.

Was the interviewer playing around?

Answer Source

A stateless component is a component that doesn't use React's this.setState() or this.getState(). You can declare it in two ways:

  • Extending React.Component and making sure that this.setState() and this.getState() aren't used
  • Declaring it as a function, where you cannot access this

A controlled component is one where its state is managed by the application, instead of the browser.

Think of a text input: in a standard web application you can write something in the input (for example: "John"), and the browser manages the redrawing of the text input to show what you have written. The browser controls that component. Your application doesn't need to handle that, it's an uncontrolled component.

In a controlled component you need to write that logic, and also store somewhere every relevant detail about the state of that component (for example: "John"). In React you usually achieve this with this.setState(), this.getState() and some event handler methods.

The interviewer was probably thinking in something similar to Redux, where you have the state of every component in the Redux Store (your single source of truth). Then you can create Stateless Components and "inject" the state via their props. You also dispatch a Redux Action for every single state change.

Prakash sharma wrote a nice example.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download