I have functional/stateless component and component which inherited from React.Component
:
const Component1 = () => (<span>Hello</span>) class Component2 extends React.Component { render() { return (<span>Hello</span>) } }
How can I determine if component is stateless or not? Is there any official way?
isStateless(Component1) // true isStateless(Component2) // false
A functional component is always a stateless component, but the class component can be stateless or stateful. There are many distinct names to stateful and stateless components.
React Programming Pattern One of the most common programming patterns in React is to use stateful parent components to maintain their own state and pass it down to one or more stateless child components as props. The example code shows a basic example. // This is a stateless child component.
A stateless function component is a typical React component that is defined as a function that does not manage any state. There are no constructors needed, no classes to initialize, and no lifecycle hooks to worry about. These functions simply take props as an input and return JSX as an output.
Before the introduction of hooks, functional components were stateless. However, with React 16.8, you can implement states with the useState hook to create a stateful component (just like the class component).
you can check it's prototype, for example:
function isStateless(Component) { return !Component.prototype.render; }
Class components are inherently stateful, but with the introduction of React hooks functional components are no longer called stateless because they can be stateful, too.
isReactComponent
special property exists on React.Component
since React 0.14. This allows to determine whether a component is class component.
function isFunctionalComponent(Component) { return ( typeof Component === 'function' // can be various things && !( Component.prototype // native arrows don't have prototypes && Component.prototype.isReactComponent // special property ) ); } function isClassComponent(Component) { return !!( typeof Component === 'function' && Component.prototype && Component.prototype.isReactComponent ); }
Similar checks are performed in React code base.
Since components can be various things like context Provider
or Consumer
, isFunctionalComponent(Component)
may not be equal to !isClassComponent(Component)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With