← react hacks / react / accessing-refs-with-useref-hook.md

Harnessing the Power of useRef Hook in React

A concise guide on how to access refs in React using the useRef Hook. Dive into the essentials with examples and code snippets.

React’s useRef Hook allows us to access and interact with elements in the DOM directly. It retains its mutable .current property across multiple renders, making it a great tool for preserving values without re-rendering components.

Here’s a simple example of how useRef can be used:

import React, { useRef } from 'react';

function ExampleComponent() {
  const inputRef = useRef();

  const handleClick = () => {
    inputRef.current.focus();
  };

  return (
    <div>
      <input ref={inputRef} type="text" />
      <button onClick={handleClick}>Focus the input</button>
    </div>
  );
}

export default ExampleComponent;

In this example, useRef is used to create a reference (inputRef) to an input element. The handleClick function triggers a focus on this input when the button is clicked.

Remember, useRef does not notify you when its content changes. Mutating the .current property won’t cause a re-render. If you need to run some code when React attaches or detaches a ref to a DOM node, you may want to use a callback ref instead.

Keep experimenting!

Quick hacks and tips from my daily workflow. Found this useful? Let me know.

@samuellawrentz →

$ ls ../react | head -4

More hacks

cd ../react →
  1. 3450e43 Enhancing Your Coding Experience with Neovim: A Beginner’s Guide

    tag: neovimtag: codingtag: productivity

  2. 9676c32 Understanding Neovim: How to Customize and Improve Your Text Editor

    tag: neovimtag: text-editortag: customization

  3. 2c098c3 Avoiding Unnecessary Re-renders with React.memo

    tag: reacttag: web developmenttag: performance optimization

  4. c2ffa3b Optimizing React Apps with useCallback

    tag: reacttag: useCallbacktag: optimization

00:00

This helps me increase the session time of my site. Thank you!

Can you stay a bit longer?