Sobes.tech
Middle

What are stateful and stateless components?

sobes.tech AI

Answer from AI

Stateful components are components that store and manage their internal state. They can change their state during operation, which affects the display or behavior of the component. In React, for example, these are class components with state or functional components with useState hooks.

Stateless components are components that do not have their own state and depend only on the props passed to them. They are simpler, easier to test, and reusable.

Example of a stateless component in React:

function Greeting(props) {
  return <h1>Hello, {props.name}!</h1>;
}

Example of a stateful component in React:

import React, { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);
  return (
    <div>
      <p>Counter: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increase</button>
    </div>
  );
}
What are stateful and stateless components? — Frontend - sobes.tech