What's the difference between `useRef` and `createRef`?

Asked
Active3 hr before
Viewed126 times

9 Answers

differenceuseref
90%

Difference between useRef and CreateRef:,Difference between C and C++,Difference between Intel and AMD,Difference between DFA and NFA

Step 1: Create a React application using the following command:

npx create - react - app react - ref
load more v
88%

createRef always returns a new ref, which you'd generally store as a field on a class component's instance. useRef returns the same ref upon every render of a functional component's instance. This is what allows the state of the ref to persist between renders, despite you not explictly storing it anywhere.,useRef(initValue) also returns a ref { current: initValue } akin to React.createRef(). Besides, it memoizes this ref to be persistent across multiple renders in a function component.,The difference is that createRef will always create a new ref. In a class-based component, you would typically put the ref in an instance property during construction (e.g. this.input = createRef()). You don't have this option in a function component. useRef takes care of returning the same ref each time as on the initial rendering.,React.createRef() is a factory returning a ref { current: null } - no magic involved.

Here's an example app demonstrating the difference in the behavior of these two functions:

import React, { useRef, createRef, useState } from "react";
import ReactDOM from "react-dom";

function App() {
  const [renderIndex, setRenderIndex] = useState(1);
  const refFromUseRef = useRef();
  const refFromCreateRef = createRef();
  if (!refFromUseRef.current) {
    refFromUseRef.current = renderIndex;
  }
  if (!refFromCreateRef.current) {
    refFromCreateRef.current = renderIndex;
  }
  return (
    <div className="App">
      Current render index: {renderIndex}
      <br />
      First render index remembered within refFromUseRef.current:
      {refFromUseRef.current}
      <br />
      First render index unsuccessfully remembered within
      refFromCreateRef.current:
      {refFromCreateRef.current}
      <br />
      <button onClick={() => setRenderIndex(prev => prev + 1)}>
        Cause re-render
      </button>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
load more v
72%

Both React APIs are used to create a mutable object. The mutable object’s properties can be changed at will without affecting the Component’s state.,These APIs create these mutable objects which can be called refs. They hold a reference to any value we want.,React.createRef are used in class components to create refs.,For example, if we change the above function App to use createRef:

Example: browsing through shared React components ib bit.dev
class App extends React.Component {    componentDidMount() {        this.divRef = React.createRef()    }    render() {        return (            <div>                <div id="divR" ref={this.divRef}>App, here</div>            </div>        )    }}
load more v
65%

createRef resets at every single render and always re-create its value while useRef always persists the data till the component is not unmounted from DOM.,So to verify, in the case of useRef, the variable will not be created on very render and always persist the same value that was on initial rendering.,Because the difference is that createRef will always return a new ref on every render occur while in the case of useRef takes care of returning the same ref each time as it was on the initial rendering.,But in the case of createRef, it will be created at every render when there is a state change and it initialize its .current property to null while in case of useRef, its current property will not be null.

App.js

import React, { useRef, createRef } from "react";
import NameInput from "./NameInput";

const App = () => {
  const useRefInput = useRef();

  const createRefInput = createRef();

  const handleUseRef = () => {
    useRefInput.current.focus()
  }

  const handleCreateRef = () => {
    createRefInput.current.focus()
  }
  return (
    <div>
      <div className="ref1">
        <NameInput ref={useRefInput} />
        <button onClick={handleUseRef}>
            Click here to focus Input using useRef
        </button>
      </div>
      <div className="ref2">
        <NameInput ref={createRefInput} />
        <button onClick={handleCreateRef}>
            Click here to focus Input using create Ref
        </button>
      </div>
    </div>
  );
}

export default App;
load more v
75%

Well, the difference is that createRef will return a new ref on every render while useRef will return the same ref each time.,As you can see, refFromUseRef persists its value even when the component rerenders while refFromCreateRef does not,useRef returns a mutable ref object whose .current property is initialized to the passed argument (initialValue). The returned object will persist for the full lifetime of the component. ,🚀 useRef Hook is more than just to manage DOM ref and it is definitely not createRef doppelganger. useRef can persist a value for a full lifetime of the component. However, note that the component will not rerender when the current value of useRef changes, if you want that effect, use useState hook instead 👏👏👏

import {createRef} from 'react' 

const FocusInput = () => {
   const inputEl = createRef()

   const focusInput = () => {
      inputEl.current.focus()
   }

   return (
      <>
         <input ref={inputEl} type="text" />
         <button onClick={focusInput}>Focus input</button>
      </div>
   )
}
load more v
40%

The difference between createRef and useRef is that createRef creates a new ref on every render in function components.,The difference between the useRef hook and the createRef function is that the useRef hook holds its value between re-renders in a function component.,In this article, we’ll look at the difference between the useRef hook and the createRef function in React components., No Comments on What’s the Difference Between useRef and createRef in a React Component?

For instance, if we have:

import React, { createRef, useEffect, useState } from "react";

export default function App() {
  const [count, setCount] = useState(0);
  const ref = createRef();

  useEffect(() => {
    ref.current = "foo";
  }, []);

  useEffect(() => {
    console.log(count, ref.current);
  }, [count]);

  return (
    <div className="App">
      <button onClick={() => setCount((c) => c + 1)}>increment</button>
      <p>{count}</p>
    </div>
  );
}
load more v
22%

…it seems like useRef can be replaced with createRef.,Here's an example app demonstrating the difference in the behavior of these two functions:,PS I believe React team better chose different naming for useRef to avoid confusion with createRef. Maybe useAndKeep or even usePermanent.,You can't set a new value for createRef. But you can for useRef.

Looking at their example…

function TextInputWithFocusButton() {
  const inputEl = useRef(null);
  const onButtonClick = () => {
    // `current` points to the mounted text input element
    inputEl.current.focus();
  };
  return (
    <>
      <input ref={inputEl} type="text" />
      <button onClick={onButtonClick}>Focus the input</button>
    </>
  );
}

…it seems like useRef can be replaced with createRef.

function TextInputWithFocusButton() {
  const inputRef = createRef(); // what's the diff?
  const onButtonClick = () => {
    // `current` points to the mounted text input element
    inputRef.current.focus();
  };
  return (
    <>
      <input ref={inputRef} type="text" />
      <button onClick={onButtonClick}>Focus the input</button>
    </>
  );
}
load more v
60%

The difference is that createRef will always create a new ref. In a class-based component, you would typically put the ref in an instance property during construction (e.g. this.input = createRef()). You don't have this option in a function component. useRef takes care of returning the same ref each time as on the initial rendering.,Here's an example app demonstrating the difference in the behavior of these two functions:,In your second example, the ref would be re-created upon every render.,createRef always returns a new ref, which you'd generally store as a field on a class component's instance. useRef returns the same ref upon every render of a functional component's instance. This is what allows the state of the ref to persist between renders, despite you not explictly storing it anywhere.

Here's an example app demonstrating the difference in the behavior of these two functions:

import React, { useRef, createRef, useState } from "react";
import ReactDOM from "react-dom";

function App() {
  const [renderIndex, setRenderIndex] = useState(1);
  const refFromUseRef = useRef();
  const refFromCreateRef = createRef();
  if (!refFromUseRef.current) {
    refFromUseRef.current = renderIndex;
  }
  if (!refFromCreateRef.current) {
    refFromCreateRef.current = renderIndex;
  }
  return (
    <div className="App">
      Current render index: {renderIndex}
      <br />
      First render index remembered within refFromUseRef.current:
      {refFromUseRef.current}
      <br />
      First render index unsuccessfully remembered within
      refFromCreateRef.current:
      {refFromCreateRef.current}
      <br />
      <button onClick={() => setRenderIndex(prev => prev + 1)}>
        Cause re-render
      </button>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
load more v
48%

173 What's the difference between `useRef` and `createRef`?,reading What's the difference between useRef and createRef? ,0 How can you make a createRef/useRef not target the last value. But rather go to where its suppose to,5336 What's the difference between using "let" and "var"?

gives quit different answers what exactly thees to do, is there a clear inside about thees to methods ?

function Interface() {

    const [solution, setSolution] = useState(0);
  
    const solutionInp = useRef();
    //                --createRef();
    
    const onButtonClick = () => {
    // `current` points to the mounted text input element
    setSolution( solutionInp.current.value)
      };


return (
 
<input
 type="text"
 // value={solution}
 
 ref={solutionInp}
 // onInput={(e) => setSolution(e.target.value)}
 />
 </section>
<button type="button" onClick={onButtonClick}>do</button>
)}


Other "difference-useref" queries related to "What's the difference between `useRef` and `createRef`?"