Hello World with Stateless Functions
suggest changeStateless components take their philosophy from functional programming, which implies that a function always returns the same result for the same inputs.
For example:
const statelessSum = (a, b) => a + b;
let a = 0;
const statefulSum = () => a++;
As you can see, statelessSum always returns the same value for a given a and b. statefulSum does not return the same value, even though it takes no parameters. That behaviour is a side effect: the function changes something beyond its return value.
So it is advisable to use stateless components more often, because they are free of side effects and always behave the same way. That is what you want in an app, because fluctuating state is the hardest case 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 can be written as simple JavaScript functions. These are called Stateless Functional Components because they are a function only of props, with no state to keep track of. (Hooks, added in React 16.8, later let function components hold state.)
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" />, document.getElementById('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.