useRef Hook In React
Tags: javascript, tutorial, react, beginners
Published: 2022-03-10 12:39:31


 
# useRef

[Demo](https://gregpetropoulos.github.io/UseRef-Demo/)
[repo](https://github.com/GregPetropoulos/UseRef-Demo)


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](https://reactjs.org/docs/hooks-reference.html#useref)


###### *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);
```


Code Set Up:
Create a folder and open up VScode and run create react app commands [CRA](https://create-react-app.dev/docs/getting-started/). Once your set up trim the folder down to bare essentials see my [repo](https://github.com/GregPetropoulos/UseRef-Demo) and update the following three files:


## App.css
```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;
}


```

## App.js
```javascript
import './App.css';
import UseRefHook from './UseRefHook';

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

export default App;

```
## UseRefHook.js
```javascript
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
```
#### Run npm start in the CLI and you should see this

 ![npm start setup](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i8ib0zbpo45ms63vt0oc.png)

The useRef hook has one property called 
```
.current
``` 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'/>
``` 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
```javascript
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

```
 
 ![Console of values](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/68e3wcptl01zzwr7mhpc.png)

```javascript
//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
 ```

## Lets See Some Action 

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

UseRefHook.js
```javascript
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
```

![Hook in Action](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4k73n72z34tjybs72b2f.png)

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

## Links :link:
[Demo](https://gregpetropoulos.github.io/UseRef-Demo/)
[repo](https://github.com/GregPetropoulos/UseRef-Demo)
[Hooks](https://reactjs.org/docs/hooks-reference.html)
[useRef](https://reactjs.org/docs/hooks-reference.html#useref)

:heart::heart::heart:

## Social 
[Twitter](https://twitter.com/GregoriosPetro1)
[Linkedin](https://www.linkedin.com/in/greg-petropoulos/)
[Portfolio](https://gregpetropoulos.dev/)
[Github](https://github.com/GregPetropoulos)

:metal:
## Happy Coding