useRef

All about useRef hook in React


  • Hook that allows creating mutable reference that persist across the component's lifecyle (similar to a mutable variable in Rust)
  • Will not cause a re-render when updateed or changed its value.
  • Useful for storing any value that can mutate, such as identifier, DOM element, counter, etc

useRef vs useState

  • when a state is modified, useRef() does not trigger a re-render of the component. Stores a mutable value that persists across the component's lifecycle.
  • when a state is modified, useState() triggers a re-render of the component. Stores a immutable value that persists across the component's lifecycle.
import React, { useRef } from 'react';
 
function ExampleComponent() {
  const inputRef = useRef(null);
 
  const handleButtonClick = () => {
    inputRef.current.focus();
  };
 
  return (
    <div>
      <input ref={inputRef} type="text" />
      <button onClick={handleButtonClick}>Focus Input</button>
    </div>
  );
}