useEffect hook corresponds to componentDidMount and componentDidUpdate depending on what we pass to the dependency array as the second parameter of useEffect method
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;
Top comments (2)
There are a couple of things to mention here
useEffect
also hascomponentDidUnmount
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.
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.
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!