# useRef Hook

## useRef Hook&#x20;

`useRef` hooks allows us to create a reference to the DOM element inside of a functional component. Unlike state variables managed by `useState`, changing the value of a `useRef` does not trigger a re-render of the component.

The `useRef` hook can be used for various purposes, including accessing and modifying DOM elements, storing previous values, or holding any mutable value that you want to persist between renders.

{% tabs %}
{% tab title="App.js" %}

```jsx
import React, {useState, useRef} from "react"

function App(){
    // Set state
    const [todoItem, setTodoItem] = useState("")
    const [todoList, setTodoList] = useState([])
    
    // Set the initial value as `null` (before DOM renders)
    const inputRef = useRef(null)
    
    // Handle todo input
    function handleChange(e){
        setTodoItem(e.target.value)
    }
    
    // Handle todo list 
    function addTodo(e){
        e.preventDefault()
        setTodoList(prevTodoList => [...prevTodoList, todoItem])
        setTodoItem("")
        
        // add `focus` method to referenced html input element 
        inputRef.current.focus()
    }
    
    // Map todo items
    const todos = todoList.map(todo => <p key={todo}> {todo} </p>)
    
    return(
         <div>
            <form>
                // React provides `ref` props to hold value of `useRef`
                <input ref={inputRef} type="text" name="todo" value={todoItem} onChange={handleChange}/>
                <button onClick={addTodo}>Add todo item</button>
            </form>
            // Show todo items
            {todos}
        </div>
    )
}

export default App
```

{% endtab %}

{% tab title="index.js" %}

```jsx
import React from "react"
import ReactDOM from "react-dom"

import App from "./App"

ReactDOM.render(<App />, document.getElementById("root"))
```

{% endtab %}
{% endtabs %}

```jsx
console.log(inputRef)
// {current: <input type="text" name="todo" value>}
```

{% hint style="info" %}
&#x20;`useRef` provides a property called `current` which holds reference to our html input element we provide to `ref` props&#x20;
{% endhint %}
