Less Common Hooks

Some hooks like “useLayoutEffect” may be required in special cases. It is also not commonly used. This lesson will detail both “useRef” and “useLayoutEffect” hooks.

We'll cover the following

useRef Hook

You can use useRef hook to get the ref of a DOM node. Later, you can use this ref for certain actions related to that node. For example, scrolling to an element position.

Other use cases may require getting the height of a DOM node or focusing an input.

useRef provides the ref object with the current property set to the reference of node in DOM.

The following example demonstrates useRef hook usage. On line #4, this hook is called to get the initial ref object. Later, set the ref property on a div to this object on line #11.

Go to top button triggers handleClick event handler. handleClick function simply scrolls the page to the position of the div with text Top section. You can see here that the topSection.current property is used to get access to the DOM node.

Get hands-on with 1400+ tech skills courses.