Skip to content

Today I Learned - 2023-08-08

Posted on:August 8, 2023 at 01:03 AM

Today, I’m continuing to do a deep dive on the various React Hooks by taking notes while reading through useRef.

Main purpose of useRef: reference a value that’s not needed for rendering

What does it mean when you should not write or read ref during rendering (except during initialization)?

Manipulating the DOM with a ref - Steps

  1. Declare a ref object with initial value of null
import { useRef } from 'react';

function Component() {
  const divRef = useRef(null);
// ....
}
  1. Pass your ref object as ref attribute to the JSX of the DOM node you want to manipulate:
//...
return ( <div ref={divRef}> </div>)
  1. Upon DOM node creation and rendering - React sets the current property of your ref object to that assigned DOM node.
  2. To access the particular DOM node of the corresponding ref object, you can use methods like focus().
function grabDiv() {
  divRef.current.focus() 
}

Next up: