
React: Mixins Considered Harmful - tilt
https://facebook.github.io/react/blog/2016/07/13/mixins-considered-harmful.html
======
janci
I like how core features of React are being considered harmful. First it was
component internal state, now it's mixins and next thing will be the lifecycle
methods.

React components will then boil down to pure render functions. React will then
be replaced by simpler VirtualDOM implementation. JS function declaration
boilerplate will be removed from render functions, so they will be more HTML
with some JS as the other way around. Also they will be called templates.

We are getting back to good-old-days PHP-style webcoding, but with few HUGE
improvements.

1\. no globals, mostly pure functions

2\. no business logic in templates, but in easy-to-reason-about redux-style
state reducers

3\. client-side rendering / isomorphic apps possible

~~~
danabramov
_> First it was component internal state_

You won’t find any place in React docs that claims internal state is harmful.
There are some guides claiming that but this is _not_ the official position
(and I say this as author of Redux and a member of React team). We use state a
lot at Facebook, and it’s a large part of what makes React useful.

 _> next thing will be the lifecycle methods._

Lifecycle methods are also fine. Sure, it’s best when there aren’t too many
and they don’t do too much, but it’s a supported feature for a reason. It is
occasionally super useful. They aren’t going away.

 _> React components will then boil down to pure render functions. React will
then be replaced by simpler VirtualDOM implementation._

This is an explicit non-goal of React. We think stateful components with
lifecycle methods are very useful. If you don’t agree, however, React is
indeed not the best choice for you, as it does too much.

I’ve read a lot of misconceptions around React so I plan to put up “Design
Goals” document in the repo so people can get a better idea of the direction
that we’re moving into, and why.

~~~
janci
> _You won’t find any place in React docs that claims internal state is
> harmful._

But it is the first principle of Redux

 _The state of your whole application is stored in an object tree within a
single store._ [1]

Am I getting it wrong?

> _I plan to put up “Design Goals” document in the repo_

That would be great. The "why" is sometimes hard to understand.

[1][http://redux.js.org/docs/introduction/ThreePrinciples.html](http://redux.js.org/docs/introduction/ThreePrinciples.html)

~~~
danabramov
I think you are confusing React with Redux. They are two very different
things. You can use them together but Redux is not the “default” way of using
React.

 _> But it is the first principle of Redux_

Redux is a _very_ opinionated library and it is not related to React in any
way. React does not officially endorse Redux. _If_ (and that’s a big if!)
React patterns don’t scale for you or if you personally _prefer_ Redux to
them, you can use it, but a Redux app !== a React app.

Which doesn’t mean either of them is the “right” or “wrong” way. Learn React
first and try to use it. If you have issues related to state or if you’re just
curious, you can also learn Redux to compare their approaches. If you like,
you can combine them, or use them separately.

~~~
janci
I had an impression, that React community (not the authors) considers Redux as
an best-practice. My first post was a little bit exaggerated view on where is
this whole React-based website developement (including Redux and other
libraries and tools) going, not only the React itself.

~~~
danabramov
_> I had an impression, that React community (not the authors) considers Redux
as an best-practice._

A part of React community, yes. Another part, no. Guess which part is vocal
because they can write tutorials, examples, articles that generate clicks? ;-)
I am as guilty of this as anyone of course, if not the most.

Obviously React has some deficiencies addressed by Redux. So does Redux have
deficiencies addressed by React. Eventually some of the ideas from Redux might
make it back into React.

However I suggest learning to build apps with React itself first before using
more radical approaches like Redux. You’ll benefit immensely from knowing both
ways. I would not necessarily put trust into articles saying “X is the best
practice” or “Y is an inferior paradigm”. I would, however, listen to somebody
who says “we tried X and Y, and here’s what worked best for us and why”.

 _> My first post was a little bit exaggerated view on where is this whole
React-based website developement (including Redux and other libraries and
tools) going, not only the React itself._

Ah okay, sorry then! These are both interesting, albeit different directions.
I think it’s easy to misunderstand them as an “evolution” whereas it’s really
a “fork” (in the traditional, non-technical sense). These are two separate
ways, and both lead to interesting but different things.

~~~
janci
I did. I started with React itself. Then I added Redux (first time, it was
beacause of the project manager decision).

I really like the state reducers.

I find internal state clumsy, beacause you have three kinds of functions
around the very same state object - get initial state, get state after some
props changed and get state after some user action. For simple cases they are
very similar to repeatedly write, but still different to abstract out.

I hate putting everything in One-Rules-Them-All Redux Store (specially form
input on each key press), beacause it creates too much little components to
glue it all together - Action declaration, action generator, reducer
implementation, projection from Store to component's props

I did not see any good solutions that take best of both approaches and I was
tired searching. But I plan to wrap my brain around this and think about what
exactly is bothering me and how to solve that. In first sight it is what I
outlined in my first post. The next thing comes to my mind are Redux-style
reducers for component's internal state.

~~~
danabramov
I hope this helps:

    
    
        dispatch(action) {
          this.setState(prevState => reducer(prevState, action))
        }

~~~
assertchris
Hmmm, that'd be sweet in a mixin...

 _ducks_

------
mikegerwitz
I'm not familiar with React's mixins, but I get the impression from the
suggestion to use higher order functions that it doesn't allow overriding
methods from other mixins. E.g. Scala's concept of stacking.

For those interested in the concept in JS, I implemented a full trait system
in GNU ease.js designed around Scala's approach, with support for stackable
traits. The system also supports protected/private properties and methods,
which can also be taken advantage of in traits to provide public and protected
APIs, and keep state encapsulated in traits. I don't have documentation
available yet (soon), but I do have a great many test cases that demonstrate
various aspects:

[https://www.gnu.org/software/easejs/#traits](https://www.gnu.org/software/easejs/#traits)
[https://www.gnu.org/software/easejs/news.html#d9b86c1](https://www.gnu.org/software/easejs/news.html#d9b86c1)

Hopefully others find this to be interesting even if they don't agree with
ease.js itself.

------
ThePhysicist
The decorator-based approach sounds interesting, but (in my understanding) it
will require moving the data fetching logic away from the main component into
the decorator, which also creates a level of indirection that is intransparent
to the component user, and I imagine stacking several of these decorators on
top of each other should provide plenty of room for unforeseen side effects as
well.

Personally, I think almost all components should be "dumb": They should just
receive the stuff that they display as properties from their parent components
and report changes back through callbacks. They should not perform any
"controller logic" beyond form validation and input serialization. Only a few
components at the top should be responsible for fetching and distributing
resources from the backend. Typically, it should suffice to have an
"Application" component that takes care of fetching stuff that every other
component should see (e.g. data about the user), while components one level
below the application should fetch stuff that is specific to the given
page/view that is being displayed.

Unfortunately, compared to the humble beginnings a few years ago I feel that
the whole React.js stack gets more and more bloated these days. As an example,
managing state through Redux requires writing actions, reducers and
implementing a subscriber pattern in my components, just to fetch some data
from the server. I mean, if we're writing a version of "Photoshop" for the
browser this level of complexity might be warranted, but in most cases we just
want to fetch some JSON, display it nicely formatted to the user, let him/her
click on it and possibly send some data back. If we need 500 kB of Javascript
libraries to do that while having to patch/reinvent many other things that we
took for granted before -like simple hyperlinks (I'm looking at you, react-
router)-, chances are we're doing it wrong.

~~~
danabramov
_> it will require moving the data fetching logic away from the main component
into the decorator_

We are not suggesting you to do anything like this.

The article was about migrating _from mixins_ to patterns like higher order
components. If you do your data fetching right in the component, we are not
suggesting you to change anything. It’s only mixins that we found problematic,
and we are just sharing our experience migrating away from them.

 _> the whole React.js stack gets more and more bloated these days. As an
example, managing state through Redux requires writing actions, reducers and
implementing a subscriber pattern in my components, just to fetch some data
from the server_

Redux has nothing to do with the “React stack”. React is just React; if
fetching data in components works great for you, why are you migrating to
Redux?

 _> I mean, if we're writing a version of "Photoshop" for the browser this
level of complexity might be warranted, but in most cases we just want to
fetch some JSON_

Redux _is_ overused. Nowhere in the article do we recommend to use Redux. The
article is about mixins.

~~~
ThePhysicist
Thanks for clarifying this! Maybe I misunderstood the example in the article
that migrates the subscription logic from the component/mixin into the
decorator. This was what made me question whether this will be more
efficient/scalable than using the Mixin approach, as there is also some
indirection here.

Concerning the whole Redux issue: Yes, of course I can -and do- use React
without it, but the problem is that everyone else seems to rely on these tools
and see them as an integral part of the "React experience". I find this
problematic as it makes many components less portable, as they are bound to a
given router / state loading paradigm.

I think it would be great if there could be a bit more emphasis on "keeping it
simple" in the React tutorials, as I see a lot of (often unneeded) complexity
popping up in the frontend world, and I think this will cause a lot of issues
in the future.

~~~
danabramov
_> migrates the subscription logic from the component/mixin into the
decorator._

It was not migrating the logic from the component. The example was about
getting rid of a mixin. I think the article even mentions the opposite:

“If there is just one component subscribed to this data source, it is fine to
embed the subscription logic right into the component. Avoid premature
abstractions.

 _> the problem is that everyone else seems to rely on these tools and see
them as an integral part of the "React experience"_

Who is “everyone else”? I think you might be listening to a vocal bubble. As
Redux author, I can tell you that it is not in any way essential to React.
Some people use it, many people don’t. Solve _your_ problems, don’t just
follow what you see in flashy magazines.

 _> I think it would be great if there could be a bit more emphasis on
"keeping it simple" in the React tutorials_

I think this is exactly what React tutorials do:

* [https://facebook.github.io/react/docs/tutorial.html](https://facebook.github.io/react/docs/tutorial.html)

* [https://facebook.github.io/react/docs/thinking-in-react.html](https://facebook.github.io/react/docs/thinking-in-react.html)

We can’t really control what third party tutorials write.

~~~
ThePhysicist
Thanks again for clarifying, I don't want to criticize the work of the React
authors or the community (which is outstanding), I'm just voicing what I
observe from my "vocal bubble". Maybe I really spend too much time on HN :D

~~~
danabramov
Yea, no problem. HN can be super misleading. I suggest to build apps and learn
from the experience instead. ;-)

------
leogcrespo
Awesome post Dan, thanks for writing and sharing!

One thing caught my attention:

 _> At Facebook, we extensively use traits in Hack which are fairly similar to
mixins. Nevertheless, we think that mixins are unnecessary and problematic in
React codebases. Here’s why._

 _> Mixins introduce implicit dependencies_

 _> Mixins cause name clashes_

 _> Mixins cause snowballing complexity_

When I read these three reasons, I actually felt identified with them even
outside React, since these as pretty generic problems in "mixin-like" cases
that I've seen, for example Ruby modules. So it got my attention the fact that
you're (at Facebook) using Hack traits successfully. Why is that? Are any of
those reasons you stated not true with Hack traits? (Maybe you don't have
knowledge in Hack though, but any high level conceptual idea may help).

Again, awesome post!

~~~
asQuirreL
Traits and mixins are different. A trait/interface/protocol doesn't generally
contain implementation, and when it does, it is based only on other methods in
the trait (for things like default implementations), whereas mixins are just
fragments of a class implementation with potentially arbitrary dependencies on
methods.

So traits document the dependencies that mixins make implicitly.

Traits in typed languages can only cause name clashes if two methods in
different traits have the same name and the same type signature. This is
immediately obvious, and the compiler will warn you so you can fix it there
and then when you try and implement them both for one class. (It also brings
into question whether there should be another trait to hold that shared
method).

The snowballing complexity that is mentioned stems from all those implicit
dependencies: There's no way of knowing what they all could be in a nest of
related mixins, whereas the corresponding traits document it and provide a
map, of sorts.

~~~
leogcrespo
Thanks for your response.

I can see how type checking helps with that in Hack, that makes a lot of
sense.

Guess that in the case of Ruby for example we'd still have the same
disadvantages as in JS right? Since there's still the possibility of calling
methods in other modules and even in the class where the module is included,
since that is discovered at runtime and you don't have any hierarchy that
restricts who can call what.

------
bcherny
Implementing mixins correctly in JS (which React does not) is already a well
explored problem space.

I like [https://leanpub.com/javascript-
spessore](https://leanpub.com/javascript-spessore) for great explorations and
derivations of various mixin patterns.

It's not that mixins are bad in general, it's that React doesn't implement
them well in particular.

~~~
braythwayt
Thank you!

The code in JavaScript Spessore is ES5-specific, but I stand by the ideas
discussed, including the one central to TFA:

    
    
      Naïve mixins solve the many-to-many dependency problem,
      but not the open recursion problem.
    

You can read the book online for free, but if you prefer the ebook format,
here is a coupon for a free copy, good for today only:

[http://leanpub.com/javascript-
spessore/c/hackernews](http://leanpub.com/javascript-spessore/c/hackernews)

~~~
bcherny
Wow! Very cool to have the infamous Reggie drop in. Perhaps this is a good
chance to say thank you for JS Allonge, which was my introduction to writing
proper JavaScript. Before it I wrote code to make a feature work; now, it is
equal parts getting it to work and crafting something elegant. Thank you!

------
ludwigvan
I believe as time passes, we are moving away from the simplicity that made
React win. Flux, Redux, higher order components generate too much complexity
most of the time. React used to be simple, it still is, but the ecosystem and
the mentality has gotten needlessly complex.

~~~
spicyj
If simple things were possible before with React, then they still are, and
that's not changing. You don't need Flux and Redux a lot of the time; in my
experience they're overused and React component state is underused.

I agree the community mentality of adding lots of complexity on top is a
problem. We're working on improving this, but if you have ideas I'd be
interested to hear them too.

~~~
nathancahill
> "in my experience they're overused and React component state is underused"

Thank you, I've felt the same way. A lot of projects take "ALL STATE MUST BE
IN THE STORE" to an extreme.

~~~
sotojuan
Which is funny because you'll never hear that from Dan or any other authors.

~~~
nathancahill
ikr

------
n0us
I personally moved all my projects away from mixins a while ago when I first
heard they were deprecated. At first I was frustrated because of JS churn but
this certainly was the right move.

For anyone who is apprehensive, the shift in thinking from using mixins to
HOCs was not so difficult even if it's initially puzzling.

Quick edit: forgot to mention that this shift made my code way easier to
understand in some places and thus the initial investment saves dev time in
the long run.

~~~
thatswrong0
I'm a fan of HOCs as well. My only problem with them is that I'm also a fan of
shallow testing, and HOCs don't play nicely with shallow testing. I'm waiting
on something like this
([https://github.com/airbnb/enzyme/issues/250](https://github.com/airbnb/enzyme/issues/250))
to get implemented

~~~
coderzach
Why not just mock the HOC to be the identity fn? `(Component) => Component`

~~~
eiriklv
This is my preferred approach as well - and it (anecdotally) works great,
since you can then just manually inject any props/spies as needed like any
other "dumb" component.

Edit: But he might be pointing to the testing of the actual HOCs/component
decorating functions.

------
charlysisto
It's funny to see in the life cycle of every new language/framework in the
block the rediscovery of good architectural patterns that can be summed up in
one sentence: \- inheritance & mixin bad / composition good.

Good article nevertheless.

~~~
vog
_> inheritance & mixin bad / composition good_

This wisdom is at least as old as the classic GoF book [1] which was published
in 1994. Many of their patterns can be summarized as: "Favor 'object
composition' over 'class inheritance'."

They also give a pretty simple, compelling reason for that: It is just a
direct consequence of the even more fundamental principle:

"Program to an interface, not an implementation."

[1] Gang of Four (Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides):
"Design Patterns: Elements of Reusable Object-Oriented Software"
[https://en.wikipedia.org/wiki/Design_Patterns](https://en.wikipedia.org/wiki/Design_Patterns)

~~~
charlysisto
I would argue that the more intuitive principle behind composition is the
"Single Responsibility" one. Although it is correlative to the idea of
'program to an interface' (aka don't mingle with the state from the inside of
an object that is not for you to do) I find it easier to grasp.

While i'm at it I'll add that the main reason SRP is so important is because
it limits combinatorial explosions of state, so you can keep control, test and
reason about it - incidentally the main idea behind the success of React.js

------
jameslk
That's too bad, mixins were simple to grasp and worked really well. The oft
suggested alternative to mixins is higher order components. Here's one of my
favorite quotes[0] on the matter:

> _You lose so much with [higher order components], especially with es6:_

> _You lose the (original) class, and with it, the ability to compose it, to
> extend it and …. reflection. All your components are [the higher order
> component]. For example, you cannot rely on the Class.name in es6._

> _You lose the ability to extend the component and expose extra members. Your
> higher order component will not ‘pass’ that through._

> _The above two basically renders the ability to compose several decoupled
> and agnostic one to the other “higher level components” impossible._

> _It is verbose and non-declarative , and basically much less readable and
> maintainable._

If there's a better pattern than mixins, I would say its _traits_ [1]. For
some reason, I don't find it used much often in the wild. I'm not sure it
would be practically applied to React anyway without ending up with mixins
again, but at least the concept would be clearer: there should be no shared
state and dependencies are explicit.

0\. [https://medium.com/@danikenan/you-lose-so-much-with-your-
sol...](https://medium.com/@danikenan/you-lose-so-much-with-your-solution-
especially-with-es6-bcf4fdad40be#.u0e6qabr1)

1\.
[https://en.wikipedia.org/wiki/Trait_%28computer_programming%...](https://en.wikipedia.org/wiki/Trait_%28computer_programming%29)

~~~
danabramov
_> the ability to compose it, to extend it and …. reflection_

In our experience those are precisely the things that can turn codebases into
a mess. It’s great that you can manage the complexity from inheritance and
reflection, but in our experience most people had problems with these patterns
(me included). On the other hand, we found that React composition model is
enough to express everything we needed in the apps, and we didn’t miss
inheritance or reflection.

------
eiriklv
Great post Dan. Just out of curiosity - what's your goto approach for
replacing examples like the SetIntervalMixin
([https://facebook.github.io/react/docs/reusable-
components.ht...](https://facebook.github.io/react/docs/reusable-
components.html#mixins)) with a HOC? I can't seem to find something that feels
very elegant for these cases.

~~~
danabramov
I’d probably create a class that lets me schedule intervals on its instance,
and call `this.scheduler.dispose()` in `componentWillUnmount()`. I don’t think
accidentally forgetting to dispose of it is a big problem as it’s easy to
catch in a code review. But if it concerns you, HOC could work for this as
well. In the future, we might build some helpers for this into React itself.

~~~
eiriklv
Yup - that's more or less what I've ended up with. Just wanted to hear you if
you had a better solution at hand. It's pretty much an edge case example, as
99% of all this stuff fit perfectly into the HOC way of thinking. The
remaining cases won't add any more context/complexity than using mixins do
anyway.

Thanks for all your hard work!

------
digisth
Mixins have their place, but perhaps we are at the point where we need general
advice (like the class "Prefer composition over inheritance") for mixins
("Prefer traits over mixins"), especially as there's a good analog between the
two. Matthijs Hollemans wrote an article which argues for that as well:

[http://matthijshollemans.com/2015/07/22/mixins-and-traits-
in...](http://matthijshollemans.com/2015/07/22/mixins-and-traits-in-swift-2/)

------
Cshelton
For those of you complaining about "javascript complexity":

I think one of the biggest misunderstandings about JS and a large portion of
the community complaining about "churn rate", is that JS does not have a churn
problem, it has an inexperienced developer problem. Which is not to say that
is a bad thing, JS/web is the first language for MANY programmers now.

When you get stuck on learning this framework vs that framework, or a
antipatterns within a framework and "complexity" being added to a framework,
take a look back and understand the WHY first.

Many ideas and the fundamental design of React are not new. Infact, they are
very old, even before there was such thing as the internet. Functional
programming patterns, also very old. Immutability, a very old concept.
Composing rather than inheriting, old concept. Eliminating all side effects
(through immutability and composition), very old concept.

The idea of a "higher order component", is not new, nor does it have any
direct relation to React. It is a design pattern. This article is simply
teaching you a design pattern that aligns with the design patterns React was
built upon and works very well. Instead of complaining about React and "added
complexity", I encourage you again, to ask why. Learn why this blog post, from
the React core team, recommends doing it this way. It is in no way a
requirement. React is just a tool. It is just Javascript. It is just
programming. Welcome to the development world.

Also, understand the problems you are trying to solve. Facebook uses these
design patterns because they have thousands of components at a massive scale.
The majority of users will not be working on something of that size. Don't
feel like you have to use everything that comes out and is available in the
React ecosystem. Infact, I would urge you, never start using something UNTIL
you come across a problem and need to find a solution. It is a common thing
for inexperienced developers to feel the need to incorporate everything they
have read about, when they are using them to "solve" problems they don't
understand, nor even have. This applies to problem solving in general, not
just React, not just programming.

TL;DR Understand WHY something is used in the way it is before throwing it out
as "too complex". Don't solve problems you do not have, until you need to
actually solve them. If you do use a pattern/tool/etc., understand the WHY.
(Don't use Higher Order Components or redux if you have not had the need for
them and do not understand the problem they solve.) Also understand that many
design patterns coming to JS are not a result of JS churn, they have been
around a long time and have a very good reason for existing. JS churn is not
real, it is a misunderstanding of using a solution in a world that has many
solutions available.

~~~
mrrobot2
0.3 - 0.1 = 0.19999999999999998

~~~
fbonetti
Floating point error, present in every language that uses floats. This is in
no way unique to JavaScript.

~~~
mrrobot2
Talk is cheap, give an example in code.

~~~
insin
Python REPL:

    
    
        >>> 0.3 - 0.1
        0.19999999999999998
    

Ruby REPL:

    
    
           0.3 - 0.1
        => 0.19999999999999998

~~~
mrrobot2
[https://repl.it/Cbqb](https://repl.it/Cbqb) unless your Python compiler runs
on some sort of JavaScript (-:

~~~
mrrobot2
And while you're at it, do you know of any other language that does this?
[http://pasteboard.co/bbM0qneiQ.jpg](http://pasteboard.co/bbM0qneiQ.jpg)

------
abalone
"Considered Harmful" Essays Considered Harmful:
[http://meyerweb.com/eric/comment/chech.html](http://meyerweb.com/eric/comment/chech.html)

~~~
danabramov
I don’t think there’s anyone writing Considered Harmful articles who hasn’t
ready that essay but thanks! ;-)

------
wmccullough
I'll likely catch some hell, but there's a reason mixins are considered an
anti-pattern in most languages...

~~~
spicyj
Yup, no news here. For people who already know that, this was designed as a
post with specific examples that tend to pop up in React codebases and advice
about how to migrate away from them.

------
iandanforth
I worry this suggests an opposition to inheritance in general. Sharing code
through class hierarchy is incredibly useful and common. I'd hate for ES6 to
add decent classes and then have React push people away from 'extends'. But
perhaps I'm reading too much into this.

~~~
danabramov
_> I worry this suggests an opposition to inheritance in general. Sharing code
through class hierarchy is incredibly useful and common._

This is indeed opposition to inheritance in general, precisely because we
tried it, and it doesn’t work great in React apps. React has a strong
composition model that does not _need_ inheritance.

[https://discuss.reactjs.org/t/best-practices-for-
extending-s...](https://discuss.reactjs.org/t/best-practices-for-extending-
subclassing-components/1820/2)

Of course you are free to use inheritance for other purposes. (Or even React
components if you insist.) But as the team behind this library, we strongly
suggest you to use composition instead of inheritance when defining React
components.

~~~
iandanforth
This is incredibly unfortunate. I feel like this attitude will turn off and
hamper a lot of potential users. It smacks of functional proselytizing and it
is not appreciated.

~~~
danabramov
We are sharing what worked for us. Why would be encouraging people to use
patterns that did not work well for us?

------
nikki93
Why not just prototype inheritance with multiple inheritance? Like Self. The
class-instance duality is removed then, and everything is just an editable
object. This always made the most sense to me. Then just having the 'universe'
be a map of id->obj with prototype inheritance, then editing the universe
being reduxy and just a reduce over the objects, with the reduce polymorphised
over the object's inheritance (this is the benefit of OO, really, not mutable
update)--brings wins of functional, prototype, OO all together.

------
skwosh
It's not clear to me why (in the pattern presented) the decorators don't
return a subclass (which would preserve the dynamic and static properties and
methods, etc). Instead you get hacks like `hoist-non-react-statics` to copy
them over manually.

For context, the article advocates the following:

    
    
        import GlobalClass from 'global-class'
    
        const decorator = SuperClass =>
            class extends GlobalClass {
    
                render() {
                    return <SuperClass {...etc}></SuperClass>
                }
    
            }
    

This can be rewritten to remove the fixed dependency on `GlobalClass`, while
preserving the underlying type:

    
    
        const decorator = SuperClass =>
            class extends SuperClass {
    
                render() {
                    // const SuperClass = super.constructor // if you want to be less explicit...
                    return <SuperClass {...etc}></SuperClass>
                }
    
            }
    

The only requirement is to maintain the contract outlined by the `SuperClass`,
but that's what `super` is for. (By that I mean e.g. that `componentDidMount`
should't be overwritten without also calling super.componentDidMount()
before/after).

Returning a different kind class entirely limits the utility of the pattern in
general (IMO), and you lose the nice function-composition-like behaviour
provided by `super.method`.

~~~
danabramov
In our experience inheritance causes a lot of hard-to-find issues, and muddles
boundaries between component concerns. Some of the same problems I described
we had in mixins also apply to inheritance.

 _> and you lose the nice function-composition-like behaviour provided by
`super.method`._

We found this to be an anti-pattern. It’s easy to get lost in virtual calls
across hierarchy, and people _are_ going to create virtual methods (and
override them) if you allow it.

 _> Instead you get hacks like `hoist-non-react-statics` to copy them over
manually._

An alternative is to just not put static methods on component. It’s not such a
useful feature.

------
BinaryIdiot
But mixins are so easy and are used in thousands of JavaScript libraries.
Seems odd to deprecate their usage in React; why wouldn't you embrace a
typically used construct in JavaScript? The syntax without mixins just seems
overly complex. I mean sure it's still simple but more complicated than before
and certainly not intuitive (in my opinion anyway).

I just started exploring React not long ago. It's interesting but I'm not sure
it's my cup of tea just yet but most of the issues mentioned exist everywhere
with JavaScript because, well, it's a dynamic language. I would suspect many
of the issues lie outside of using mixins and more of how everything is
architected but without seeing their codebase I don't actually know that. I
just know mixins can be used, relatively easy, and cleanly as long as your
design is appropriate for them.

~~~
danabramov
_> Seems odd to deprecate their usage in React; why wouldn't you embrace a
typically used construct in JavaScript?_

Because we already _did_ embrace it, and we found that it was a mistake.

I believe that the article addresses why mixins didn’t scale well in our React
codebases. We have written a ton of React code and wanted to share our
experience.

It seems quite normal to me that our experience might not match experience of
other JavaScript users. React offers a component model based on functional
composition solution that was not quite common in JavaScript until very
recently. Paradigms are much more fundamental than languages. We found that,
with React’s paradigm, in our experience, mixins were unnecessary. For sure,
your mileage may vary.

 _> most of the issues mentioned exist everywhere with JavaScript because,
well, it's a dynamic language_

You might not believe me, but these issues had _much_ less of an impact on us
with React’s component model. And even less so after we started using gradual
static typing with Flow ([http://flowtype.org/](http://flowtype.org/)).

 _> I would suspect many of the issues lie outside of using mixins and more of
how everything is architected but without seeing their codebase I don't
actually know that._

I have been employed by Facebook for just a few months. I have written a few
relatively complex React apps myself before. I didn’t see much of a difference
between the mixins I wrote previously and mixins I saw at Facebook. In my
view, both mixins I wrote and mixins I saw at Facebook introduced similar
problems to the respective codebases.

It’s great that you know how to use mixins without shooting yourself in the
foot. This is a rare gift in my experience. Most people (like me) will overuse
them because they’re too powerful. On the other hand, components are limiting
enough that even people like me can write code that is easy to maintain in the
long term.

 _> The syntax without mixins just seems overly complex. I mean sure it's
still simple but more complicated than before._

What syntax are you referring to? I don’t think there was any new syntax in
the article. The only challenging part might be the idea of a higher-order
component, but this is not even a React feature. It’s the way JavaScript
works: you can create functions and pass arguments to them. It turns out that
we could solve one of the use cases for mixins with vanilla JavaScript
constructs and without the need for a complex mixin system.

I think you might be missing the point that we have seen _quite a bit_ of
React apps being developed. Some of the things we say might be counter-
intuitive but they come from Facebook’s extensive experience of using React
(more than 20,000 components). So when we’re saying something, it is not
theoretical or out of spite. We are trying to share our experience with you,
in the hope that you might find it useful not to repeat our mistakes.

------
sergiotapia
React dropping mixins is the #1 reason why I stopped using Meteor. Sure Meteor
has Blaze, but nobody uses it.

Before we had a nice mixin called getMeteorData:

``` var HelloUser = React.createClass({ mixins: [ReactMeteorData],
getMeteorData() { return { currentUser: Meteor.user() }; }, render() { return
<span>Hello {this.data.currentUser.username}!</span>; } }); ```

Short, simple, you knew exactly what it was doing without breaking your
wrists.

Now it's some create container lunacy that brings no benefit to most projects
except dogma "properness" \- the developer UX is just fungled beyond belief
and it makes me so sad that Meteor lost so much.

I guess my gripe in general with Javascript now is how complicated simple
things are. It's entire ecosystem is intertwined with complexity and
verbosity.

I wonder if typescript alleviates some of these pain points.

~~~
tlrobinson
I was going to sketch out a higher order component for you that does the same
thing but it looks like they've already implemented that:
[https://atmospherejs.com/meteor/react-meteor-
data](https://atmospherejs.com/meteor/react-meteor-data)

I guess this is the "create container lunacy" you're talking about?

I'm not sure what's so horrible about it, especially if you enable decorators
in Babel (admittedly non-standard syntax but it works great):

    
    
        @createContainer(() => ({
            currentUser: Meteor.user()
        }))
        export default class Foo extends Component {
             return <span>Hello {this.props.data.currentUser.username}!</span>;
        }
    

This is basically how Redux's React bindings works too.

Is it really just the syntax you're upset about, or am I missing something?

~~~
danabramov
You don’t even need that syntax. (Please don’t use decorators in examples,
they are not part of the language yet. This is super confusing.)

    
    
        function Foo(props) {
          return <span>Hello {props.data.currentUser.username}!</span>;
        }
    
        function getMeteorData() {
          return {
            currentUser: Meteor.user()
          };
        }
    
        export default createContainer(getMeteorData)(Foo)
    

Why do you see this as “lunacy” compared to mixins?

------
udarkness
Seems to be that the harmful part of the code is actually the OOP. The
solution they provide is not a direct attack vs mixins (composition, multiple
inheritance), instead they propose to use functions instead of methods but
keeping the root of the problems (methods), they may notice in the future that
the classes will bring the same issues (the parent can also have a method with
the same name...). Notice that the key solution is to use functions (pure,
deterministic). While react is a good improvement to remove states, it still
promotes objects that are still holding states. I hope they can get more
advise from their haxl team :)

------
tjholowaychuk
I kindddd of feel this way about the "global" context as well, but it's one of
those sketchy-yet-handy things haha. Though beyond react-router and redux
using it I haven't touched it personally.

~~~
Waterluvian
I will fight hard to never use globals or Singleton's. It makes my code
conceptually way more obvious but sometimes the boilerplate is just wild to
pass things like eventemitter around

------
tlrobinson
I thought this was pretty well known by now, given the lack of mixin support
in ES6 React components (and functional stateless components), but this is a
nice summary of the problems and solutions.

------
coltonv
So there are a lot of features in React that are basically getting deprecated,
like createClass in favor of ES6 components, mixins, etc. This is good that
you guys are learning as you go, my question is will you ever release a
version of React, possibly spin React off into a version which supports
deprecated APIs and a version that doesn't and is therefore smaller, faster,
and easier to maintain? Eventually you could drop support entirely for the
deprecated feature. That would be the best response to this IMO.

~~~
danabramov
We are not deprecating `createClass()` yet.

When we do, we will keep it for another major version (just like we always
approached deprecations) and then move it to a separate package so only people
who really want it would use it.

~~~
coltonv
Yeah I was just using createClass as an example of a feature that's not
strictly necessary and could be removed to slim up the library. Thanks for
responding! Any idea when you will be trimming stuff like that out? Do you
think you will you ever remove mixins?

~~~
danabramov
We don't need to remove mixins because that's one of the biggest reasons
people use createClass(). So it's enough to just separate createClass() and
then we wash our hands, and it lives its own life. We won't use it but others
are free to if they like it.

No specific timeline but we might I'd say within half a year is likely.

------
enugu
Racket has classes as first-class values. So a mixin is a function from one
class to another. This seems similar to higher order components solution.
[https://docs.racket-
lang.org/guide/classes.html?q=mixin#%28t...](https://docs.racket-
lang.org/guide/classes.html?q=mixin#%28tech._mixin%29)

~~~
danabramov
Similar but the big difference is the wrapping component _does not extend_ the
wrapped component. It uses React component model for composition.

------
rayshan
I see some React code using decorators but this article doesn't mention them.
I'd love to get everyone's opinion on whether decorators are also an anti-
pattern, even if decorators become a JavaScript standard.

~~~
danabramov
Since they are not part of the standard, we are not going to take a stance on
them yet. We do, however, think that it is very risky to adopt experimental
language features unless they are very simple (like object spread operator).
In my personal experience people often misunderstand how decorators work, and
the tooling often breaks, so I would not recommend them with React _yet_.

------
jpsierens
The higher order function example in ES6:

[https://jsfiddle.net/jpsierens/obgh1uc7/2/](https://jsfiddle.net/jpsierens/obgh1uc7/2/)

------
pjmlp
Apparently React is already moving from "Technology X will solve all problems"
to "Technology X considered harmful" pattern.

------
welder
From my extensive experience using Backbone, Angular, and now React:

React and SPAs Considered Harmful

I keep seeing dependency bloat, over-engineering, unnecessary complexity, all
with SPAs not providing the basic things Django/Flask do easily. A good
explanation here:

[https://medium.com/@wob/the-sad-state-of-web-
development-160...](https://medium.com/@wob/the-sad-state-of-web-
development-1603a861d29f)

If you're going to use React, use it on one page don't make your whole
site/app a single page app.

------
daliwali
It doesn't fare well that a framework that is only 3 years old already has an
extensive list of anti-patterns and tons of statements on what not to do. Also
having to do manual performance optimizations using the framework is a hassle
to application developers and can be a major pitfall (ex. PureRenderMixin,
shouldComponentUpdate).

~~~
nathancahill
No, no, no. This is exactly what makes React so great compared to Angular (to
pick one). There's One Way™ to do things correctly. Using anti-pattern "hacks"
will work for a little bit, but in the long run come back to bite you as your
software grows and scales.

I've been using React for over 2 years now, and still refer back to that list
when I feel like something isn't right.

~~~
Bahamut
Huh? This sounds like it's more true of Angular than React - there is a widely
adopted style guide, and well-known anti-patterns are very established. I
don't get that impression with React.

~~~
nathancahill
I added "to pick one" because I don't particularly want to start a flame
thread over frameworks. Everyone can choose their own tools for their jobs.

However, to the point about style guide/anti-patterns: I guess we haven't been
working in the same codebases.. I've worked on a handful of different projects
and most have scope flying all of the place, with controllers and directives
used interchangeably (not to mention factories/services/providers). But really
my biggest gripe is the amount of logic that ends up in disparate HTML
attributes. JSX is a much cleaner solution.

~~~
Bahamut
Well, I commented mainly because of this

> There's One Way™ to do things correctly. Using anti-pattern "hacks" will
> work for a little bit, but in the long run come back to bite you as your
> software grows and scales.

This is true, but in the given context that this is not true in the Angular
world, that is definitely false. Some of the things you've mentioned are
considered known abuses/anti-patterns/etc.

~~~
Sacho
I'd consider large parts of the Angular 1 framework to be anti-patterns. I
believe that's the reason why they completely remade the framework with
Angular 2, to avoid all these pitfalls. Given that, I find it the complaint
that React is doing the same odd :)

------
rukuu001
Does that mean the LinkedStateMixin is going away?

~~~
danabramov
Yes, eventually.

------
Double_Cast
So uh, HOC's are basically monads. Right?

~~~
danabramov
I think the intuition might be a little bit related but AFAIK monad is a very
specific thing (can “lift” something and map functions over it, or at least
that’s what I remember from a monad tutorial), and HOCs are different (they
just wrap components). “Decorator” might be a closer pattern.

I would say HOC is more like a regular higher order function... which is why
it’s called this way. :P

~~~
smadge
I agree, a "higher order component" just isn't a monad. A HOC is just good old
fashioned object composition. I think you are right to call it the decorator
pattern. It annoys me how React ,and in general the entire javascript
ecosystem, reinvents the wheel, then gives their invention another name.

~~~
danabramov
It’s not quite object composition though. We are not forwarding any method
calls or containing the instances. HOCs are much closer to functional
composition than to object composition.

------
anaclet0
Coming from ember 1.x, mixins are pure evil

------
kimmshibal
I ported my app from React to Vue in 2 days. Couldn't be happier

~~~
danabramov
That sounds great. Evan put a lot of effort in Vue, and it’s satisfying to see
it paying off! While this is very tangential to the article, could you
elaborate on what you struggled with in React? We are always looking out for
things we could improve.

------
hardwaresofton
Did facebook just rediscover that mixins are an anti-pattern? I would have
expected them to know that going in, figured they had just thought it was fine
as long as they convinced people to use them very sparingly

~~~
zpao
No we've known and said it for a long time but not very loudly. People haven't
used them sparingly and they tend to infect a codebase. Now we're just making
a more concerted effort to communicate more broadly that they can be bad.

~~~
hardwaresofton
Thanks for replying -- I assume in whatever planning/architecture meetings
went on before react was released that this was a measured decision you all
chose to take, weighing the potential dangers less dangerous than the initial
usefulness. Is this assumption correct?

If you could do it again, would you leave in mixins or would you keep them
out?

~~~
zpao
It was the right decision at the time - it made React much more familiar for
people at FB who were writing PHP/Hack (Dan called this familiarity out in the
post). It also enabled some great things that are still awkward with other
patterns - [https://github.com/reactjs/react-timer-
mixin/issues/4](https://github.com/reactjs/react-timer-mixin/issues/4) is an
interesting case. That functionality is nice and elegant with mixins but not
so with classes.

I think if we had to do it again (and get to keep the knowledge of the last
few years), we'd probably skip mixins. We'd surely do some other things
differently too though :)

