How to Implement Functional Components in React
This article provides a straightforward guide on how to implement functional components in React. You will learn the fundamental syntax for creating these components, how to pass data using props, and how to manage state and lifecycle methods using React Hooks.
Creating a Basic Functional Component
A functional component in React is simply a JavaScript function that returns React elements (JSX). The modern standard is to use ES6 arrow function syntax.
Here is the simplest implementation of a functional component:
import React from 'react';
const WelcomeMessage = () => {
return <h1>Welcome to React!</h1>;
};
export default WelcomeMessage;To use this component in another part of your application, you import it and render it like an HTML tag:
import WelcomeMessage from './WelcomeMessage';
const App = () => {
return (
<div>
<WelcomeMessage />
</div>
);
};Passing Data with Props
Functional components accept a single argument called
props (properties), which is an object containing data
passed down from a parent component.
Here is how to implement a component that uses props:
const UserProfile = (props) => {
return (
<div>
<h2>User: {props.username}</h2>
<p>Role: {props.role}</p>
</div>
);
};You can simplify this code by using ES6 destructuring directly in the function arguments:
const UserProfile = ({ username, role }) => {
return (
<div>
<h2>User: {username}</h2>
<p>Role: {role}</p>
</div>
);
};Managing State with the useState Hook
To add state to a functional component, you must use the
useState Hook. This hook returns an array with two
elements: the current state value and a function to update it.
Here is how to implement a stateful functional component:
import React, { useState } from 'react';
const Counter = () => {
const [count, setCount] = useState(0);
return (
<div>
<p>Current Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
};Handling Side Effects with the useEffect Hook
To handle side effects (such as fetching data, updating the DOM, or
setting up subscriptions), use the useEffect Hook. This
hook serves a similar purpose to lifecycle methods like
componentDidMount, componentDidUpdate, and
componentWillUnmount in class components.
Here is an implementation of useEffect that runs once
when the component mounts:
import React, { useState, useEffect } from 'react';
const DataFetcher = () => {
const [data, setData] = useState([]);
useEffect(() => {
fetch('https://api.example.com/items')
.then((response) => response.json())
.then((data) => setData(data));
}, []); // The empty dependency array ensures this runs only once
return (
<ul>
{data.map((item) => (
<li key={item.id}>{item.name}</li>
))}
</ul>
);
};