🚀New Article:React State and Lifecycle – Managing Dynamic Data(useEffect)🚀
we’re diving into State and Lifecycle in React, two critical concepts that allow components to manage and respond to dynamic data and changes over time.
What Is State in React?
State is an object that holds dynamic data specific to a component. Unlike props, state is mutable and managed within the component. Changes to state trigger a re-render, updating the UI automatically.
Example of State:
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click Me</button>
</div>
);
}
export default Counter;
In this example, count is a state variable, and setCount updates it.
What Are Lifecycle Methods?
Lifecycle methods are hooks that allow you to execute code at specific points in a component’s lifecycle, such as when it mounts, updates, or unmounts.
In functional components, React provides hooks like useEffect to manage lifecycle events.
What is useEffect in React?
useEffect is a special function in React that allows you to perform side effects in your components. Side effects are actions that happen outside of the React rendering process, such as:
It is part of React's Hooks system and is used in functional components.
How Does useEffect Work?
The useEffect function takes two arguments:
The basic syntax looks like this:
useEffect(() => {
// Your side effect code here
}, [dependencies]);
When Does useEffect Run?
If ywe do not provide a dependency array, useEffect will run after every render (initial render + updates).
useEffect(() => {
console.log("Effect runs after every render!");
});
If we provide an empty array, useEffect will run only once when the component is first rendered (like componentDidMount in class components).
Recommended by LinkedIn
useEffect(() => {
console.log("Effect runs only once!");
}, [ ]);
If we include variables in the dependency array, useEffect will run only when those variables change.
useEffect(() => {
console.log("Effect runs when `count` changes!");
}, [count]);
Sometimes, you need to clean up resources when a component is removed or before the effect runs again. For example, if you set up a timer, you should clear it to avoid memory leaks.
To do this, return a cleanup function from your effect:
useEffect(() => {
const timer = setInterval(() => {
console.log("Timer running");
}, 1000);
return () => {
clearInterval(timer); // Cleanup the timer
console.log("Timer cleaned up");
};
}, [ ]);
Lifecycle Phases in React
Example
useEffect(() => {
console.log("Component mounted!");
}, [ ]);
2. Updating (Component Re-render)
useEffect(() => {
console.log("State or props updated!");
});
3. Unmounting (Component Removal)
Example:
useEffect(() => {
return () => {
console.log("Component unmounted!");
};
}, [ ]);