← react hacks / react / use-effect-for-lifecycle-events.md

Mastering useEffect for React Lifecycle Events

Unpack the power of React's useEffect Hook for managing lifecycle events. Learn to write clean, effective code with examples.

React’s useEffect hook allows you to handle lifecycle events in your functional components. It’s like combining componentDidMount, componentDidUpdate, and componentWillUnmount in class components.

Here’s a basic usage of useEffect:

import React, { useEffect } from 'react';

function App() {
  useEffect(() => {
    // Your code here
  }, []);

  return <div>My App</div>;
}

In the example above, the function passed to useEffect will run after the render is committed to the screen. Think of it as componentDidMount and componentDidUpdate combined.

To mimic componentDidMount, pass an empty array [] as the second argument to useEffect:

useEffect(() => {
   // This will run ONCE after initial render, similar to componentDidMount
}, []);

To mimic componentDidUpdate, you can pass specific values in the array:

useEffect(() => {
  // This runs AFTER every render, ONLY IF `prop` has changed since last render
}, [prop]);

To mimic componentWillUnmount, return a function from within the function passed to useEffect:

useEffect(() => {
  // component cleanup
  return () => {
    // This will run when the component unmounts, similar to componentWillUnmount
  };
}, []);

Master useEffect to write clean, robust, and efficient React code!

Keep experimenting!

Quick hacks and tips from my daily workflow. Found this useful? Let me know.

@samuellawrentz →

$ ls ../react | head -4

More hacks

cd ../react →
  1. 3450e43 Enhancing Your Coding Experience with Neovim: A Beginner’s Guide

    tag: neovimtag: codingtag: productivity

  2. 9676c32 Understanding Neovim: How to Customize and Improve Your Text Editor

    tag: neovimtag: text-editortag: customization

  3. c52b973 Harnessing the Power of useRef Hook in React

    tag: reacttag: hookstag: useRef

  4. c2ffa3b Optimizing React Apps with useCallback

    tag: reacttag: useCallbacktag: optimization

00:00

This helps me increase the session time of my site. Thank you!

Can you stay a bit longer?