How to add a Stateful component without a constructor class in React?


We can add a stateful component without using a constructor class by using the useState hook. This hook allows us to create and update state within our component without the need for a constructor. To use this hook, we simply call the useState function and pass in our initial state as an argument.

There are primarily two ways of creating React Components −

  • Using JS classes.

  • Using functional components.

Before react v16 there was no way of adding state to functional components. But since the inception of React Hooks we can write stateful functional components as well.

A stateful functional component in React is a component that is defined as a JavaScript function and uses the useState hook to manage and manipulate its internal state. These components are similar to stateful class components, but they do not require the use of a class or a constructor. Instead, the useState hook is used to initialize state, and the component can access and update the state using the values and functions returned by the hook.

Stateful functional components are simpler and more lightweight than class components, and they are the recommended way to create stateful components in React. They are easy to write, understand, test and debug.

Approach

  • Create a functional component using the function keyword.

function MyComponent(props) {
   return <h1>Hello, {props.name}</h1>;
}
  • Use the useState hook to add state to the component. The useState hook takes an initial value as an argument and returns an array with two elements: the current state and a function to update it −

function MyComponent(props) {
   const [count, setCount] = useState(0);
   return (
      <>
         <h1>Hello, {props.name}</h1>
         <button onClick={() => setCount(count + 1)}>Click me</button>
         <p>You have clicked {count} times</p>
      </>
   );
}
  • Use the state and the update function as needed within the component's JSX −

function MyComponent(props) {
   const [count, setCount] = useState(0);
   return (
      <>
         <h1>Hello, {props.name}</h1>
         <button onClick={() => setCount(count + 1)}>Click me</button>
         <p>You have clicked {count} times</p>
      </>
   );
}
  • Import the ‘MyComponent.js’ file in index.js

import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import MyComponent from "./MyComponent";
const rootElement = document.getElementById("root");
const root = createRoot(rootElement);
root.render(
   <StrictMode>
      <MyComponent />
   </StrictMode>
);

Note − You can add multiple states and use multiple useState hooks in a functional component.

Output

Updated on: 13-Feb-2023

504 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements