DEV Community

Discussion on: Understanding useEffect() lifeCycle hook in React with Examples

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