Functional components in React are a simpler way to write components that only render UI and do not have their own state or lifecycle methods. These components are essentially JavaScript functions that take in props and return React elements.
Basic Functional Component
import React from 'react';
function Greeting(props) {
return Hello, {props.name}!
;
}
export default Greeting;
Using Hooks with Functional Components
With the introduction of React Hooks in version 16.8, functional components can now manage state and side effects. The most commonly used hooks are useState and useEffect.
1. useState Hook
The useState hook allows you to add state to a functional component:
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
You clicked {count} times
);
}
export default Counter;
2. useEffect Hook
The useEffect hook allows you to perform side effects in functional components. It can be used for things like fetching data, updating the DOM, and setting up subscriptions:
import React, { useState, useEffect } from 'react';
function Timer() {
const [count, setCount] = useState(0);
useEffect(() => {
const interval = setInterval(() => {
setCount(prevCount => prevCount + 1);
}, 1000);
return () => clearInterval(interval); // Cleanup on component unmount
}, []);
return {count} seconds passed
;
}
export default Timer;
Advantages of Functional Components
- Simplicity: Functional components are easier to read and write.
- Performance: They may offer performance benefits due to less overhead compared to class components.
- Hooks: With hooks, functional components can now handle state and side effects, making them almost as powerful as class components.
Key Points
- No ‘ this ‘ Keyword: Functional components do not use the this keyword, which can simplify your code and reduce potential bugs.
- Stateless to Stateful: Initially, functional components were stateless, but with hooks, they can now have state.
- Reusability: Functional components encourage reusability and composability.