Saying Goodbye to componentDidMount: Hello useEffect in React Functions

2024-07-27

Now, React lets you build things with functions instead of classes, which is awesome cause functions are simpler and more fun. But functions don't have those special moments built in. That's where "useEffect" comes in. It's like a new tool in your mongoose grip.

Think of useEffect like a promise you make to yourself. You tell it some code you wanna run after the flower blooms (when the component mounts), and it makes sure it happens. You can even tell useEffect to only run that code again if something changes, like if Baloo decides honey is more important than naps.

Here's the trick: to make useEffect act just like componentDidMount, you gotta keep its promise empty. No code inside, just like an empty beehive! That way, useEffect knows to only run once after the flower blooms.




import React, { useEffect }

function MyComponent() {
  // Code to show on screen (like Mowgli and Baloo)
  
  useEffect(() => {
    // This code runs only once after the component mounts (like blooming)
    console.log("The component is mounted on the screen!");
  }, []); // Empty dependency array, like an empty beehive
  
  return (
    <div>
      {/* Your component's JSX goes here */}
    </div>
  );
}

export default MyComponent;

This code defines a functional component MyComponent. Inside it, there's a useEffect hook. The function passed to useEffect is the code that runs after the component mounts. The empty dependency array [] tells useEffect to only run this code once, just like componentDidMount.




This is the most versatile approach. useEffect allows you to specify an array as the second argument. This array tells useEffect when to re-run the effect function. An empty array, as we saw earlier, runs the effect only once after mount. But, you can use other conditions:

  • Include a prop in the dependency array: If the effect relies on a specific prop, include it in the array. The effect will re-run whenever that prop changes.
  • Use state variables: Similar to props, including state variables in the array makes the effect re-run when the state changes.

Example (useEffect with prop dependency):

import React, { useEffect }

function UserList({ users }) {
  useEffect(() => {
    console.log("Users list updated:", users);
  }, [users]); // Re-run when users prop changes

  return (
    <ul>
      {/* Display users list */}
    </ul>
  );
}

useLayoutEffect (for DOM manipulation):

In rare cases, you might need to manipulate the DOM directly after the component mounts and before the next render (similar to componentDidMount behavior in class components). For this specific scenario, you can use the useLayoutEffect hook. However, it's generally recommended to avoid DOM manipulation in functional components and favor a declarative approach with state and JSX.

Get Initial Props (Next.js):

If you're working with Next.js, a framework built on React, you can use the getInitialProps static method for server-side data fetching. This allows you to fetch data before the component mounts on the client-side, similar to how componentDidMount might be used in class components for server-rendered applications.


javascript reactjs react-hooks



Enhancing Textarea Usability: The Art of Auto-sizing

We'll create a container element, typically a <div>, to hold the actual <textarea> element and another hidden <div>. This hidden element will be used to mirror the content of the textarea...


Alternative Methods for Validating Decimal Numbers in JavaScript

Understanding IsNumeric()In JavaScript, the isNaN() function is a built-in method used to determine if a given value is a number or not...


Alternative Methods for Escaping HTML Strings in jQuery

Understanding HTML Escaping:HTML escaping is a crucial practice to prevent malicious code injection attacks, such as cross-site scripting (XSS)...


Learning jQuery: Where to Start and Why You Might Ask

JavaScript: This is a programming language used to create interactive elements on web pages.jQuery: This is a library built on top of JavaScript...


Alternative Methods for Detecting Undefined Object Properties

Understanding the Problem: In JavaScript, objects can have properties. If you try to access a property that doesn't exist...



javascript reactjs react hooks

Unveiling Website Fonts: Techniques for Developers and Designers

The most reliable method is using your browser's developer tools. Here's a general process (specific keys might differ slightly):


Ensuring a Smooth User Experience: Best Practices for Popups in JavaScript

Browsers have built-in popup blockers to prevent annoying ads or malicious windows from automatically opening.This can conflict with legitimate popups your website might use


Interactive Backgrounds with JavaScript: A Guide to Changing Colors on the Fly

Provides the structure and content of a web page.You create elements like <div>, <p>, etc. , to define different sections of your page


Understanding the Code Examples for JavaScript Object Length

Understanding the ConceptUnlike arrays which have a built-in length property, JavaScript objects don't directly provide a length property


Choosing the Right Tool for the Job: Graph Visualization Options in JavaScript

These libraries empower you to create interactive and informative visualizations of graphs (networks of nodes connected by edges) in web browsers