🚀New Article:React State and Lifecycle – Managing Dynamic Data(useEffect)🚀

🚀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:

  • Fetching data from an API.
  • Updating the DOM manually.
  • Setting up or cleaning up timers or event listeners.

It is part of React's Hooks system and is used in functional components.

How Does useEffect Work?

The useEffect function takes two arguments:

  1. Effect Function: This is the function where you write the code for your side effect.
  2. Dependency Array (optional): A list of variables that the effect depends on. React will run the effect only when these variables change.

The basic syntax looks like this:

useEffect(() => {
  // Your side effect code here
}, [dependencies]);        

When Does useEffect Run?

  • Without Dependency Array:

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!");
});        

  • With Empty Dependency Array ([ ]):

If we provide an empty array, useEffect will run only once when the component is first rendered (like componentDidMount in class components).

useEffect(() => {
  console.log("Effect runs only once!");
}, [ ]);        

  • With Dependencies:

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]);        

  • Cleaning Up Side Effects

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");
  };
}, [ ]);        

  • Things to Remember

  1. Run Effects Conditionally: Use the dependency array to control when the effect runs. This avoids unnecessary work.
  2. Avoid Infinite Loops: Be careful not to update state inside useEffect without proper dependency control, as it can cause infinite renders.
  3. Use Cleanup: Always clean up resources like timers or event listeners to prevent memory leaks.


Lifecycle Phases in React

  1. Mounting (Component Creation)

  • Triggered when a component is created and inserted into the DOM.
  • Commonly used to fetch initial data.

Example

useEffect(() => {  
  console.log("Component mounted!");  
}, [ ]);          

2. Updating (Component Re-render)

  • Occurs when state or props change.
  • Useful for reacting to changes in data.

useEffect(() => {  
  console.log("State or props updated!");  
});          

3. Unmounting (Component Removal)

  • Triggered when a component is removed from the DOM.
  • Commonly used to clean up resources.

Example:

useEffect(() => {  
  return () => {  
    console.log("Component unmounted!");  
  };  
}, [ ]);          



To view or add a comment, sign in

More articles by Mahesh Bhor

Others also viewed

Explore content categories