React Logo

React Basics: useRef Hook

Use case: You have a form field with a submit button, enter a value in the field and hit Enter and then form field still has focus, but enter a value in the field and click the submit button and the field loses focus. To restore focus to the field use the useRef hook, which is used to provide direct access to DOM nodes in functional components.


import React, {useState, useRef} from "react" 
    //don't forget to import useRef

function App() {
    const [newTodoValue, setNewTodoValue] = 
    useState("") // add todo values to state
    const [todosList, setTodosList] = 
    useState([])  // add todo list to state
    const inputRef = useRef(null)  
    // create instance of useRef
    function handleChange(event) {
    function addTodo(event) {
        //prevent form from going all the way
        setTodosList(prevTodosList => 
        [...prevTodosList, newTodoValue]) 
        //copy existing todos, 
		    // add new todo value
        //clear out the form field for 
        immediate reuse
        //use the current.focus() of 
        useRef to apply focus to the 
		  //applied DOM node
    const allTodos = => {todo}) 
    //spit out the todosList, formatted
    return (
                <input ref={inputRef} 
                type="text" name="todo" 
                // the "ref" attribute applies the 
				// useRef hook to the DOM element
                <button onClick={addTodo}>
                    Add todo item</button>
            //display the entire mapped todo list

export default App