Sitemap

What are components and useState in React?

2 min readMay 14, 2025

--

In React, components are reusable and independent building blocks of the user interface, functioning similarly to JavaScript functions but returning HTML. The React useState Hook allows us to track state in a function component. State generally refers to data or properties that need to be tracked in an application. They come in two types: functional components and class components, with functional components being the modern standard, often used with Hooks.
useState is a React Hook that allows functional components to manage state, or dynamic data that can change over time. It takes an initial value as an argument and returns an array containing the current state value and a function to update it. When the state is updated using this function, React re-renders the component to reflect the changes in the UI. This Hook is crucial for handling user interactions and dynamic content within components.
Code

import React, { useState } from ‘react’;

function ExampleComponent() {
const [count, setCount] = useState(0);

return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
count is the state variable, initialized to 0, and setCount is the function used to update it. Each click on the button increments the count and triggers a re-render, updating the displayed count.

Functional Components: These are simple JavaScript functions that return JSX (React’s syntax for rendering UI). They do not have their own state unless you use hooks like useState.

jsx
function Greeting() {
return <h1>Hello, Abayomi!</h1>;
}

Get ABAYOMI ABOGUNRIN’s stories in your inbox

Join Medium for free to get updates from this writer.

Class Components: These are ES6 classes that extend React.Component and have their own state and lifecycle methods.

jsx
class Greeting extends React.Component {
render() {
return <h1>Hello, Abayomi!</h1>;
}
}

useState in React
useState is a React Hook that allows functional components to manage state. Before hooks, only class components could have state. With useState, functional components can now handle state efficiently.

How useState Works:
It returns an array with two elements:
State variable: Holds the current state value.
Setter function: Updates the state.

Example:
jsx
import React, { useState } from “react”;

function Counter() {
const [count, setCount] = useState(0); // Initial state is 0

return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increase</button>
</div>
);
}

export default Counter;

--

--