What is functional component in React?
Answer
A functional component in React is a type of component that is defined as a JavaScript function. It is a simpler way to define a component compared to a class component. Functional components are stateless, meaning they do not have their own state and do not use lifecycle methods. They are used to display data and receive props from a parent component. Functional components are useful for creating reusable UI elements that do not require complex logic or state management. They are also faster to render compared to class components because they have a smaller memory footprint. Here is an example of a functional component that displays a list of items passed down as props:
function ItemList(props) {
return (
<ul>
{props.items.map(item => (
<li key={item.id}>{item.name}</li>
))}
</ul>
);
}
In this example, the ItemList component receives an array of items as props and maps over them to display each item as a list item. The key prop is used to uniquely identify each item in the list. Functional components can also use React hooks to manage state and lifecycle methods. The useState hook is used to add state to a functional component. Here is an example of a functional component that uses the useState hook to toggle a button:
import React, { useState } from 'react';
function ToggleButton() {
const [isOn, setIsOn] = useState(false);
function handleClick() {
setIsOn(!isOn);
}
return (
<button onClick={handleClick}>
{isOn ? 'ON' : 'OFF'}
</button>
);
}
In this example, the ToggleButton component uses the useState hook to add a boolean state value called isOn and a function to update it called setIsOn. The handleClick function is called when the button is clicked and toggles the isOn state value. The button text is updated based on the isOn state value. Overall, functional components are a powerful tool in React for creating reusable UI elements and managing state and lifecycle methods using hooks. They are a simpler and faster alternative to class components for components that do not require complex logic or state management.
Related React job interview questions
What is difference between functional and class component?
React JuniorWhat is class component in React?
React JuniorDo hooks replace high order components in React?
React JuniorWhat happens if you attempt to update the state directly in React?
React JuniorWhat are the React lifecycle stages?
React Junior