DEV Community

Cover image for useRef Hook In React
Greg
Greg

Posted on

useRef Hook In React

useRef

Demo
repo

The useRef hook in React is a quick and easy way to access and mutate a DOM element without causing a state change or re-render. useRef docs

*Disclaimer: When you need to make state changes use the useState hook. Using the useRef hook in place of the useState hook is an anti-pattern.

useRef looks like this:

const box = useRef(initialValue);
Enter fullscreen mode Exit fullscreen mode

Code Set Up:
Create a folder and open up VScode and run create react app commands CRA. Once your set up trim the folder down to bare essentials see my repo and update the following three files:

App.css


 * {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
  font-size: 24px;
}

body {
  font-family: 'Courier New', Courier, monospace;
  background-color: rgba(148, 30, 9, 0.76);
  color: whitesmoke;
  line-height: 1.8;
}
.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  max-width: 768px;
  margin: auto;
  padding: 0 20px;
}

label,
h1,
label {
  text-align: center;
  width: 200px;
}
button {
  background-color: dodgerblue;
  color: honeydew;
  height: 50px;
  width: 100px;
  margin: 16px;
}


Enter fullscreen mode Exit fullscreen mode

App.js

import './App.css';
import UseRefHook from './UseRefHook';

function App() {
  return (
    <>
      <UseRefHook />
    </>
  );
}

export default App;

Enter fullscreen mode Exit fullscreen mode

UseRefHook.js

import React from 'react'

export const UseRefHook = () => {
  return (
    <div className="container">
    <h1>useRef Demo</h1>
    <form>

    </form>
    <label htmlFor='box'>Box Input </label>
    <input type='text' id='box'/>
    <button type='submit'>Enter</button>
  </div>
  )
}
export default UseRefHook
Enter fullscreen mode Exit fullscreen mode

Run npm start in the CLI and you should see this

npm start setup

The useRef hook has one property called

.current
Enter fullscreen mode Exit fullscreen mode


and it's an object holding the mutable value passed to it.

By passing an object to the ref attribute

<input type='text' ref ={box} id='box'/>
Enter fullscreen mode Exit fullscreen mode


We gain access to the DOM node and the .current property is set to the value.

Check The Console

See this in the console.logs in the onSubmit function

UseRefHook.js

import { useRef } from 'react';

 export const UseRefHook = () => {
  const box = useRef();

  const onSubmit = (e) => {
    e.preventDefault();
    console.log(box);
    console.log(box.current);
    console.log(box.current.value);
  };
  return (
    <div className='container'>
      <h1>useRef Demo</h1>
      <form onSubmit={onSubmit}>
        <label htmlFor='box'>Box Input </label>
        <input type='text' ref={box} id='box' />
        <button type='submit'>Enter</button>
      </form>
    </div>
  );
}
export default UseRefHook

Enter fullscreen mode Exit fullscreen mode

Console of values

//The current object
console.log(box); // {current: input#box}

//The DOM node 
console.log(box.current); //{current: input#box}

//The value of the DOM node
console.log(box.current.value); //hello world
Enter fullscreen mode Exit fullscreen mode

Lets See Some Action

I have set the value of box to change color and "Thank you" when submitted

UseRefHook.js

import { useRef } from 'react';

 export const UseRefHook = () => {
  const box = useRef();

  const onSubmit = (e) => {
    e.preventDefault();
    // console.log(box);
    // console.log(box.current);
    // console.log(box.current.value);

    // Set the value directly and this doesn't cause a re-render
    // When submitted change color of field and say Thank you
    box.current.style.backgroundColor="dodgerblue"
    box.current.value= 'Thank you'

  };
  return (
    <div className='container'>
      <h1>useRef Demo</h1>
      <form onSubmit={onSubmit}>
        <label htmlFor='box'>Box Input </label>
        <input type='text' ref={box} id='box' />
        <button type='submit'>Enter</button>
      </form>
    </div>
  );
}
export default UseRefHook
Enter fullscreen mode Exit fullscreen mode

Hook in Action

Further considerations:
useRef is not limited to a DOM node and can reference any value such as the previous state.

Links 🔗

Demo
repo
Hooks
useRef

❤️❤️❤️

Social

Twitter
Linkedin
Portfolio
Github

🤘

Happy Coding

Top comments (0)