React

What is a stateless component in React?

Stateless components in React are components that don’t manage data. For example, a stateless component might render the same thing each time, like a logo or text block, or it might just render something based on data it receives from a parent component.

Stateless Component Examples

The first example shows a functional component that always renders the same output:

function Stateless() {
  return (
    <div>
      <h1>I will never change!!!!</h1>
    </div>
  )
}

The next example is a function that receives props but is still stateless:

function StillStateless(props) {
  return (
    <div>
      <h1>I change, but only in displaying this text: {props.title}</h1>
    </div>
  )
}
function App() {
  return (
    <div>
      <StillStateless title="My Stateless Component" />
    </div>
  )
}

As you can see from the above examples, your component is stateless if we’re not handling state in our component (this.setState in classes or useState in functions).

Aren’t all functional components stateless?

Not anymore. However, with the advent of React Hooks, functional components gained the ability to manage state and use other React features previously exclusive to class-based components.

Hooks allow you to use useState, useEffect, useContext, and other built-in hooks to introduce state management and side effects within functional components. This means that not all functional components are stateless anymore.

Don’t forget to check out my React page here which contains links to common concepts and examples in React.

Also, you can follow me on Twitter/X here! And now, mastodon: @bernieslearnings@mastodon.social

Thanks for reading!

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments