Middle
Tell about hooks and the lifecycle of components in React.
sobes.tech AI
Answer from AI
In React, hooks are functions that allow you to use state and other React features in functional components, without the need to write classes. The main hooks are useState, useEffect, useContext, and others.
The component lifecycle in classes is divided into phases: mounting, updating, and unmounting. In functional components, useEffect allows you to perform side effects, mimicking lifecycle methods:
- componentDidMount — useEffect with an empty dependency array []
- componentDidUpdate — useEffect with dependencies
- componentWillUnmount — cleanup function in useEffect
Example of using useEffect:
import React, { useState, useEffect } from 'react';
function Timer() {
const [count, setCount] = useState(0);
useEffect(() => {
const timer = setInterval(() => {
setCount(c => c + 1);
}, 1000);
return () => clearInterval(timer); // cleanup on unmount
}, []);
return <div>Seconds passed: {count}</div>;
}
Thus, hooks allow for more flexible management of component state and lifecycle.