DEV Community

muneebejazz
muneebejazz

Posted on

2 1

Understanding useEffect() lifeCycle hook in React with Examples

useEffect hook corresponds to componentDidMount and componentDidUpdate depending on what we pass to the dependency array as the second parameter of useEffect method

  1. Empty dependency Array useEffect(()=> {}, [])
    The useEffect() will run once only for the lifecycle of the
    component.

Example 1

Lets say we want to toggle (focus && display) input element whenever we press a button.

import React, { useState, useRef, useEffect } from "react";

const Test3 = () => {
  const [isEditing, setIsEditing] = useState(false);
  const textInputRef = useRef(null);
  useEffect(() => {
    console.log("useEffect Called.");
    if (isEditing && textInputRef.current) {
      textInputRef.current.focus();
    }
  }, [isEditing, textInputRef]);
  return (
    <div className="m-12 flex gap-2">
      <input
        ref={textInputRef}
        type="text"
        className={`border border-gray-400 px-3 py-1.5 rounded `}
        placeholder="Search"
        disabled={!isEditing}
      />

      <button
        className="bg-blue-500 text-white px-5 rounded"
        onClick={() => {
          setIsEditing((prev) => !prev);
        }}>
        Toggle Focus
      </button>
    </div>
  );
};

export default Test3;
Enter fullscreen mode Exit fullscreen mode

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (2)

Collapse
 
link2twenty profile image
Andrew Bone

There are a couple of things to mention here

  1. You never need to put a ref in as a dependency as they don't trigger a change in the same way.
  2. A useEffect also has componentDidUnmount by returning a function. This can be vital when working with custom event listeners.

I've also rewritten the code in a way that makes it slightly easy to read (in my opinion) but I know that's just personal preference.

export default function Form()  {
  const textInputRef = useRef(null);  
  const [isEditing, setIsEditing] = useState(false);

  // Set focus if isEditing is true
  useEffect(() => {
    const {current: input} = textInputRef;
    if (!isEditing || !input) return;

    input.focus()
  }, [isEditing]);

  return (
    <div>
      <input placeholder="Search" ref={textInputRef} type="text" disabled={!isEditing} />
      <button onClick={() => setIsEditing((prev) => !prev)}>Toggle Focus</button>
    </div>
  );
};
Enter fullscreen mode Exit fullscreen mode
Collapse
 
link2twenty profile image
Andrew Bone

Hello!

If you'd like, you can add syntax highlighting (colours that make code easier to read) to your code block like the following example.

console.log('Hello world!');
Enter fullscreen mode Exit fullscreen mode

This should make it a bit easier to understand your code. 😎

In order to use this in your code blocks, you must designate the coding language you are using directly after the first three back-ticks. So in the example above, you'd write three back-ticks js (no space between the two), put the code beneath (e.g. console.log('Hello world!');), then three back-ticks beneath that to close the code.

Here's an image that shows how it's written!

Example of how to add syntax highlighting in code blocks

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay