DEV Community

Discussion on: My first React 'aha' moment. Is this an antipattern?

Collapse
 
artmllr profile image
Art

I'd say what your original implementation was not actually as much of an antipattern as you'd think.

What you were storing inside of state was not actually HTML, but React Elements.

React Elements are what is returned from React.createElement, which is what angle braces desugar to in JSX.

Since, I'm assuming, the source of STDOUT and STDERR will always be rendered by their corresponding components, I think this is a fine solution.

I've seen elements stored in state in many components. We use it in prod for stuff like modals for example...

Collapse
 
theundefined profile image
Joe

This is very interesting. Thank you for pointing this out to me.

I see now that in both examples I am storing objects in the state. The first example is using JSX objects and the second example is using my own JSON objects.

In my second example, my own objects may be easier to manipulate across multiple rendering scenarios, but if that is not a requirement then it's additional work for the browser to transform these into JSX objects, and this output stream could theoretically stack up to contain thousands of objects.

So I agree with you, this isn't an antipattern. I am now thinking of this as a refactoring technique for re-usability that can be adopted when multiple components need to render centralized data.

Thanks for providing the example of storing JSX for modals in the state, that is a great example that is a common project requirement.

Collapse
 
artmllr profile image
Art

Glad you found that useful!

Perhaps one more thing to add, is that if you were to serialize the state (to persist it in local storage for example), you'd also have to use custom objects. React Elements are circular, so you can't easily stringify them.