Skip to main content

Avoiding Use Effect With Callback Refs

Avoid unnecessary re-renders in React by using callback refs instead of useEffect for DOM manipulation. Learn the benefits and examples here!

––– views

Avoiding useEffect with callback refs | TkDodo's blog

The Problem with useEffect

  • Many developers often reach for useEffect as their first solution for DOM manipulation
  • Using useEffect for DOM operations can lead to unnecessary re-renders and complexity

Callback Refs as a Better Alternative

  • React provides callback refs as a more direct way to interact with DOM elements
  • Callback refs are functions that React calls when an element is mounted or unmounted

Benefits of Callback Refs

  1. More Direct: They provide immediate access to DOM elements when they're mounted
  2. Better Performance: No need for extra render cycles
  3. Cleaner Code: Less code and fewer dependencies to manage

Example Use Cases

  • Focusing elements

  • Setting up third-party libraries

  • Measuring DOM elements

  • Animation initialization