Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I put react component inside state?

Can't find any recent official info if any of the three options below is allowed?

  constructor(props) {
    this.state = {
      item: <SomeItem />,
      item1: () => <SomeItem />,
      item2: SomeItem,
    };
  }

I found this answer but it references an old link from web archive which says:

What Shouldn’t Go in State? ... React components: Build them in render() based on underlying props and state.

But that link doesn't say why that is a bad idea, if it will introduce bugs, etc.

like image 988
Giorgi Moniava Avatar asked Sep 06 '25 03:09

Giorgi Moniava


1 Answers

This is a really good question.

The reason that putting components in state is advised against is just that it goes fundamentally against the React model, which is that a component provides a render method (which is a pure function) that the React engine uses to automatically update the DOM to reflect the values of the component's props and state.

The output of that render, i.e. the React Element, is supposed to be used directly by the React engine. The contract is that your app, and all its components, generate a bunch of Elements in a pure way for the React engine to manage.

By doing things like introducing side effects in render, or putting the Elements in state, you're essentially breaking the 'pure' contract and it may give unpredictable results, which may or may not be considered bugs in your application. The specifics of the bugs may even change with different versions of React, with different engine implementations. The point is that you're breaking the React contract, so whilst it may work in some cases, it also may not in others or even the same cases as React itself changes. The behaviour is not guaranteed.

React has built-in ways to cache renders based on prop values, like React.memo, that the engine provides and understands, and are part of the contract. If you want to cache render output for performance reasons, this is the way to do it.

Indeed, this is exactly why such functions are provided by the React API rather than just letting you do it yourself.

like image 80
davnicwil Avatar answered Sep 07 '25 21:09

davnicwil