connected_user
connected_user

Reputation: 936

ReactJS: Stateful children in stateless component

Does having stateful children in a stateless component make the component no-longer stateless?

Upvotes: 2

Views: 2281

Answers (2)

Tom Fenech
Tom Fenech

Reputation: 74695

Short answer

No, it doesn't.


The life-cycle methods that are associated with a component that has state should work independently of where they are in the component hierarchy, otherwise things would break in unpredictable ways.

Here's proof that stateless components have a backing instance of a class, so they can use refs and life-cycle methods:

class StatefulComponent extends React.Component {
  componentDidMount() {
    this.wrapper.classList.add("highlight");
  }
  
  render() {
    return (
      <div ref={ref => this.wrapper = ref}>
        Stateful (red outline due to class being added)
        {this.props.children}
      </div>
    );
  }
}

const StatelessComponent = props => (
  <div>
    Stateless (black outline)
    {props.children}
  </div>
);

ReactDOM.render(
  <StatefulComponent>
    <StatelessComponent>
      <StatefulComponent />
    </StatelessComponent>
  </StatefulComponent>, document.getElementById("app"));
div {
  padding: 20px;
  outline: 1px solid;
}

.highlight {
  outline-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>

Upvotes: 4

Shubham Khatri
Shubham Khatri

Reputation: 282000

State is a property privately managed by a component and hence a component being stateless is decided by its own self and not by its parents or children.

No lifecycle hooks are available within the stateless component whereas they continue to work as desired in their children.

Upvotes: 0

Related Questions