React is one of the most popular JavaScript libraries used for building user interfaces. One of the fundamental concepts in React is the notion of components. Components allow you to create distinct parts of your user interface and manage each part independently.
Components can be divided into two categories: functional components and class-based components. Over time, functional components have gained popularity due to simplicity and the power of hooks like useState and useEffect.
Each component in React can be reused, and you can combine them to build more complex user interfaces. Furthermore, components can receive data through props, allowing you to manage different behaviors and data in a single component tree.
Another great feature of components is their ability to be updated reactively. React uses a virtual DOM algorithm that allows only parts of the page that need to change to re-render. This capability results in much better performance for applications.
Example of a Simple Component
Below is a simple example of a functional component that displays a counter and a button. When the user clicks the button, the counter increases by one.
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>You have clicked {count} times.</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
export default Counter;
Line 1: React
and useState
are imported from the React library.
Line 3: This function Counter
is defined, which creates our component.
Line 6: The hook useState
is used to manage the local state of the counter, which is initialized to zero.
Line 12: In the return statement, there is a div
that contains a paragraph and a button. The paragraph displays the current count and clicking the button increases the count by one.
Line 17: The component is exported for use in other files as export default
.