Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React - how to determine if component is stateless/functional?

Tags:

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 
like image 567
madox2 Avatar asked Jan 05 '17 15:01

madox2


People also ask

Is functional components stateless in React?

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.

Are React components stateless or stateful?

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.

What are stateless function components?

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.

Are functional components stateful?

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).


2 Answers

you can check it's prototype, for example:

function isStateless(Component) {     return !Component.prototype.render; } 
like image 86
Doron Brikman Avatar answered Sep 30 '22 20:09

Doron Brikman


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).

like image 30
Estus Flask Avatar answered Sep 30 '22 18:09

Estus Flask