React: Are classes without state still considered stateless/pure? React: Are classes without state still considered stateless/pure? reactjs reactjs

React: Are classes without state still considered stateless/pure?


Short answer, no. Stateless functional components need to be simple functions.

You should take a look at the Recompose library for some really cool helpers that allow you to beef up your SFCs.

If you're trying to prevent unnecessary re-renders, you could look into onlyUpdateForKeys() or pure().

EDIT: So, I've been thinking about this a bit more and found this really great article on React component rendering performance. One of the key points in that article that pertains to your question:

Stateless components are internally wrapped in a class without any optimizations currently applied, according to Dan Abramov.

From a tweet in July 2016

So it appears that I was wrong. "Stateless Functional Components" are classes...for now. The confusing thing is that there have been performance improvements theorized:

In the future, we’ll also be able to make performance optimizations specific to these components by avoiding unnecessary checks and memory allocations.

At this point, I think the answer to your question becomes largely subjective. When you make a class that extends a React Component, any instances of your class get the setStateprototype method. Meaning you have the ability to set state. So does that mean it's stateful even if you're not using state? Thanks to @Jordan for the link to the code. SFCs only get a render method on the prototype when they are wrapped in a class by React.

To your point about wanting to bind functions, there's only two reasons I can think of that you'd want to bind the function:

  1. To give the function access to this (the instance of the component). From your example, it doesn't seem like you need that.
  2. To ensure that the function passed as a prop to a child component always retains the same identity. The wrapper function in your example seems unnecessary. The identity of the function is determined by the parent component (or mapStateToProps, or whatever HOC).

You should also take a look at React's PureComponent which does the same kind of shallow checking that the pure() HOC from recompose does.