useRef hook in reactjs

The useRef hook is the new addition in React 16.8.

The useRef is a hook that allows to directly create a reference to the DOM element in the functional component.

Syntax


#ref Syntax
const refContainer = useRef(initialValue);

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.

To understand useRef in more detail it is better to explain it with example. So here we are taking an example to explain useRef in more detail.

Note: For explaining this example will have to create a react application. That we have already done. You can also do using this command


#Create react app
yarn create react-app useref_example  

Then after using this command to run the application


#run app
yarn start

after that, we will get our fresh newly react app in the browser as shown below.

Now we open index.js file that is being looked like this

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);

reportWebVitals();

Now we modify the script for performing our target task that is to implement useRef

As we have earlier mentioned that useRef manipulates DOM elements. So, here we declare a few DOM elements like h1 and input as shown in the below code.

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
// import App from './App';
import reportWebVitals from './reportWebVitals';

const App = () => {

  return (
    <>
      <h1>This is UseRef  Example</h1>
      <input type="number" />
      <button>Submit</button>
    </>
  )
}

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);

reportWebVitals();

After changing the inside code our screen will be look like this

Then after we will define a state and useRef variable as mentioned in code below.

import React, { useState, useRef } from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import reportWebVitals from './reportWebVitals';

const App = () => {
//Declare state
  const [myNum, setMyNum] = useState(0);
//Declare useRef
  const inputOne = useRef();
  return (
    <>
      <h1>This is UseRef  Example</h1>
      <input type="number" />
      <button>Submit</button>
    </>
  )
}

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);

reportWebVitals();

After Declaring that we will create a function that will be called after the button is clicked. In side that function we have also printed useRef value and we will check what will be the output?

So now our code will be looks like this

import React, { useState, useRef } from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import reportWebVitals from './reportWebVitals';

const App = () => {
  const [myNum, setMyNum] = useState(0);
  const inputOne = useRef();

  const getNumBox = () => {
    console.log("hello world");
    console.log(inputOne);

  }
  return (
    <>
      <h1>This is UseRef  Example</h1>
      <input type="number" value={myNum}/>
      <button onClick={() => getNumBox()}>Submit</button>
    </>
  )
}

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);

reportWebVitals();

After that, we will check what the output will occur.

After clicking submit button we will get undefied as .current value. Now we will assign ref value to the input field as shown below.

import React, { useState, useRef } from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import reportWebVitals from './reportWebVitals';

const App = () => {
  const [myNum, setMyNum] = useState(0);
  const inputOne = useRef();

  const getNumBox = () => {
    console.log("hello world");
    console.log(inputOne);

  }
  return (
    <>
      <h1>This is UseRef  Example</h1>
      <input
        type="number"
        value={myNum}
        ref={inputOne}
        onChange={e => setMyNum(e.target.value)}
      />
      <button onClick={() => getNumBox()}>Submit</button>
    </>
  );
}

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);

reportWebVitals();

Now our output will look like this

Now we perform some action on this input field that I am changing the width of the input field after clicking submit button.

import ReactDOM from 'react-dom';
import './index.css';
import reportWebVitals from './reportWebVitals';

const App = () => {
  const [myNum, setMyNum] = useState(0);
  const inputOne = useRef();

  const getNumBox = () => {
    console.log("hello world");
    inputOne.current.style.width = "400px";
    console.log(inputOne);

  }
  return (
    <>
      <h1>This is UseRef  Example</h1>
      <input
        type="number"
        value={myNum}
        ref={inputOne}
        onChange={e => setMyNum(e.target.value)}
      />
      <button onClick={() => getNumBox()}>Submit</button>
    </>
  );
}

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);

reportWebVitals();

Then after our screen will be looking at this after clicking on submit button.

Keep in mind that useRef doesn’t notify you when its content changes. Mutating the .current property doesn’t cause a re-render.

If you want to run some code when React attaches or detaches a ref to a DOM node, you may want to use a callback ref instead.