Life Cycle React of functional Programming*
Just we talk about types of component generally in react .so We have:-
Functional Component -> a simple components hooks or state
Class Component -> using this.state and components
A Lifecycle of functional programming in react - Each component in react have lifecycle in three phases are mounting ,updating,unmounting.
Mounting Phase
--> Mounting phase is occurs when functional components are initially load in render and add to DOM
useState
-> it is a initial component state
useEffect
->it call the function and empty array dependency
for class Components-> componentDidMount
import {useState ,useEffect} from 'react
const App =()=>{
const [val , setval]=useState(0)
useEffect(()=>{
console.log(val)
},[])
return(
<>
<h1>updated value ----- {val}</h1>
<button onClick={()=>setval(val+1)}>Increase</button>
</>
)
}
Updating Phase
useState
: The setter function returned by useState (setCount in the example above) triggers a re-render when called, updating the component's state.
useEffect
- without an empty dependency array (or with specific dependencies): Simulates componentDidUpdate. The effect function runs after every render where the specified dependencies have changed. If no dependency array is provided, it runs after every render. This is used for side effects that need to react to changes in state or props.
import React, { useState, useEffect } from 'react';
const App=()=> {
const [val, setval] = useState(0);
useEffect(() => {
console.log('Component updated!'); // Runs on every re-render
});
useEffect(() => {
console.log('Value changed:', val); // Runs when val changes
}, [val]); // Dependency array with val
return (
<div>
<p>value is ---- {val}</p>
<button onClick={()=> setval(val + 1)}>Increment</button>
<p>Value: {val}</p>
</div>
);
}
Unmounting Phase
this phase occurs when the component is removed from the DOM.
import React, { useEffect } from 'react';
const App=()=> {
useEffect(() => {
console.log('Component mounted!');
const timer = setInterval(() => console.log('Timer running..'), 1000);
return () => {
console.log('Component unmounted!'); // Cleanup
clearInterval(timer); // Clear interval
};
}, []);
return <div>My Component</div>;
}
functional components in React manage their lifecycle through the strategic use of
useState for state management and useEffect for handling side effects and cleanup, effectively replicating the lifecycle phases found in class components.
By Deepak sen
for contact
care.deepaksen@gmail.com
Top comments (0)