DEV Community

Cover image for React Hooks: useRef()
Aden Eilers
Aden Eilers

Posted on

12 2

React Hooks: useRef()

What are React hooks?
They are functions in React that allow you to add react functionality to function based components.

What is the useRef hook
This hook is used to track values between renders and access DOM elements. The main difference between a ref and state is that updating a ref will not cause a re-render. This is especially useful if you want to track the number of renders of a component or when you want to track the previous state of a component. The syntax follows a common pattern:

const refContainer = useRef(0);
//refContainer: {current: 0}
Enter fullscreen mode Exit fullscreen mode
  • In this case, 0 is the initial value of refContainer.
  • refContainer will always be formatted as {current: someValue}

Example using useRef to access a DOM node:

import { useRef } from "react";

const App = () => {
  let element = useRef();

  const focusButtonClick = () => {
    element.current.focus()
  };

  return (
    <>
      <input ref={element} type="text" />
      <button onClick={focusButtonClick}>Focus</button>
    </>
  );
};

export default App;
Enter fullscreen mode Exit fullscreen mode
  • All React elements have a ref attribute that useRef can access.
  • Element is set as {current: <input type="text" />}
  • When the button is clicked, the input is focused.

Example using useRef to track previous state:

import { useRef, useState, useEffect } from "react";

const App = () => {
  const [input, setInput] = useState("");
  const previousState = useRef("");

  useEffect(() => {
    //previousState.current will always update to the previous state
    previousState.current = input;
  }, [input]);

  return (
    <>
      <input
        type="text"
        value={input}
        onChange={(e) => setInput(e.target.value)}
      />
      <p>Current State: {input}</p>
      <p>Previous State: {previousState.current}</p>
    </>
  );
};

export default App;
Enter fullscreen mode Exit fullscreen mode

More information about useRef can be found in the React docs: https://reactjs.org/docs/hooks-reference.html#useref

Leave comment if you have any questions or feedback.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (1)

Collapse
 
scriptkavi profile image
ScriptKavi

Many early birds have already started using this custom hooks library
in their ReactJs/NextJs project.

Have you started using it?

scriptkavi/hooks

PS: Don't be a late bloomer :P

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay