Stateless components are getting their philosophy from functional programming. Which implies that: A function returns all time the same thing exactly on what is given to it.
const statelessSum = (a, b) => a + b;
let a = 0;
const statefulSum = () => a++;
As you can see from the above example that, statelessSum is always will return the same values given a and b. However, statefulSum function will not return the same values given even no parameters. This type of function's behaviour is also called as a side-effect. Since, the component affects somethings beyond.
So, it is advised to use stateless components more often, since they are side-effect free and will create the same behaviour always. That is what you want to be after in your apps because fluctuating state is the worst case scenario for a maintainable program.
The most basic type of react component is one without state. React components that are pure functions of their props and do not require any internal state management can be written as simple JavaScript functions. These are said to be Stateless Functional Components
because they are a function only of props
, without having any state
to keep track of.
Here is a simple example to illustrate the concept of a Stateless Functional Component
:
// In HTML
<div id="element"></div>
// In React
const MyComponent = props => {
return <h1>Hello, {props.name}!</h1>;
};
ReactDOM.render(<MyComponent name="Arun" />, element);
// Will render <h1>Hello, Arun!</h1>
Note that all that this component does is render an h1
element containing the name
prop. This component doesn't keep track of any state. Here's an ES6 example as well:
import React from 'react'
const HelloWorld = props => (
<h1>Hello, {props.name}!</h1>
)
HelloWorld.propTypes = {
name: React.PropTypes.string.isRequired
}
export default HelloWorld
Since these components do not require a backing instance to manage the state, React has more room for optimizations. The implementation is clean, but as of yet no such optimizations for stateless components have been implemented.