W3Schools.com (2024)

The useRef Hook allows you to persist values between renders.

It can be used to store a mutable value that does not cause a re-render when updated.

It can be used to access a DOM element directly.

Does Not Cause Re-renders

If we tried to count how many times our application renders using the useState Hook, we would be caught in an infinite loop since this Hook itself causes a re-render.

To avoid this, we can use the useRef Hook.

Example:

Use useRef to track application renders.

import { useState, useEffect, useRef } from "react";import ReactDOM from "react-dom/client";function App() { const [inputValue, setInputValue] = useState(""); const count = useRef(0); useEffect(() => { count.current = count.current + 1; }); return ( <> <input type="text" value={inputValue} onChange={(e) => setInputValue(e.target.value)} /> <h1>Render Count: {count.current}</h1> </> );}const root = ReactDOM.createRoot(document.getElementById('root'));root.render(<App />);

Run Example »

useRef() only returns one item. It returns an Object called current.

When we initialize useRef we set the initial value: useRef(0).

It's like doing this: const count = {current: 0}. We can access the count by using count.current.

Run this on your computer and try typing in the input to see the application render count increase.

Get Certified!

Complete the React modules, do the exercises, take the exam and become w3schools certified!!


$95 ENROLL

Accessing DOM Elements

In general, we want to let React handle all DOM manipulation.

But there are some instances where useRef can be used without causing issues.

In React, we can add a ref attribute to an element to access it directly in the DOM.

Example:

Use useRef to focus the input:

import { useRef } from "react";import ReactDOM from "react-dom/client";function App() { const inputElement = useRef(); const focusInput = () => { inputElement.current.focus(); }; return ( <> <input type="text" ref={inputElement} /> <button onClick={focusInput}>Focus Input</button> </> );}const root = ReactDOM.createRoot(document.getElementById('root'));root.render(<App />);

Run Example »

Tracking State Changes

The useRef Hook can also be used to keep track of previous state values.

This is because we are able to persist useRef values between renders.

Example:

Use useRef to keep track of previous state values:

import { useState, useEffect, useRef } from "react";import ReactDOM from "react-dom/client";function App() { const [inputValue, setInputValue] = useState(""); const previousInputValue = useRef(""); useEffect(() => { previousInputValue.current = inputValue; }, [inputValue]); return ( <> <input type="text" value={inputValue} onChange={(e) => setInputValue(e.target.value)} /> <h2>Current Value: {inputValue}</h2> <h2>Previous Value: {previousInputValue.current}</h2> </> );}const root = ReactDOM.createRoot(document.getElementById('root'));root.render(<App />);

Run Example »

This time we use a combination of useState, useEffect, and useRef to keep track of the previous state.

In the useEffect, we are updating the useRef current value each time the inputValue is updated by entering text into the input field.

×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
[email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
[email protected]

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness
of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2024 by Refsnes Data. All Rights Reserved.W3Schools is Powered by W3.CSS.

W3Schools.com (2024)
Top Articles
Crypto Investors Defy Regulatory Uncertainty To Profit On Right To Privacy
Weekly Fundamental Bulletin: US Data Kicks Off 1st Trading Week of 2021 - Orbex Forex Trading Blog
Min Player Speed Threshold Madden 22
Quatre questions sur Temu, l'application chinoise de e-commerce qui cartonne malgré des accusations d'espionnage
Babylon Showtimes Near Cinema Cafe - Kemps River
Elie Wiesel | Books, Awards, & Facts
Muhammad Gangat on LinkedIn: #trainingcontract | 66 comments
Daisy Maldonado Muckrack
Dan Mora Growth
What The Dog Doin Origin
In ganz Hamburg: Kommt zu diesen Side Events während des OMR Festivals 2024
Realidades 2 Capitulo 2B Answers
Grace Kinstler Bathing Suit
Care First Arizona
The Equalizer 3 - The Final Chapter
Gross Net Salary Calculator Germany - 2024
Fort Bragg Cif Appointment
Pch Sunken Treasures
HLS Fetch Download tools - Chrome Web Store
How to Sell Cars on Craigslist: A Guide for Car Dealers | ACV Auctions
Commercial Credit Cards for Business Expenses | J.P. Morgan
Elektrische rolstoel ondersteuning
1800 Water Damage Princess Anne Va
Soap2Day That 70S Show
Craigslist Yard Sales Jacksonville Fl
Bgcforme Deal Biscuit
Tamilblasters.click
Bee & Willow™ 31-Piece LED Tea … curated on LTK
ZTO International tracking - Track123
Great Grady Forum
How to Tell if Battery, Alternator, or Starter is Bad
In The Heights Wiki
A Compressed Work Week Provides All Of The Following Except
Updated contract info for new secondary coach John Butler, rest of NU staff
Surfchex Seaview Fishing Pier
Austin’s Craigslist: Your Ultimate Guide to Buying, Selling, and Discovering
The Top 10 Things to Do in the Poconos
Hapi Burkett
Pcc Lancer Point Login
Hobby Lobby Pelican
The Largest Banks - ​​How to Transfer Money With Only Card Number and CVV (2024)
Google Flights Msp To Fort Myers
Behind the Casefiles - Dnepropetrovsk Maniacs - Eileen Ormsby
Here Are the Walmart Auto Services You May Not Have Heard About | Save.com
The Voice Season 22 Wiki
Uncutmazaa
O’Fallon, Illinois | Build Your Life and Family Here
Tinfoil Switch Shops
R/Mommit
Latest Posts
Article information

Author: Frankie Dare

Last Updated:

Views: 5497

Rating: 4.2 / 5 (53 voted)

Reviews: 92% of readers found this page helpful

Author information

Name: Frankie Dare

Birthday: 2000-01-27

Address: Suite 313 45115 Caridad Freeway, Port Barabaraville, MS 66713

Phone: +3769542039359

Job: Sales Manager

Hobby: Baton twirling, Stand-up comedy, Leather crafting, Rugby, tabletop games, Jigsaw puzzles, Air sports

Introduction: My name is Frankie Dare, I am a funny, beautiful, proud, fair, pleasant, cheerful, enthusiastic person who loves writing and wants to share my knowledge and understanding with you.