1/*
2 A common use case is to access a child imperatively:
3*/
4
5function TextInputWithFocusButton() {
6 const inputEl = useRef(null);
7 const onButtonClick = () => {
8 // `current` points to the mounted text input element
9 inputEl.current.focus();
10 };
11 return (
12 <>
13 <input ref={inputEl} type="text" />
14 <button onClick={onButtonClick}>Focus the input</button>
15 </>
16 );
17}
1import React, {useRef, useEffect} from "react";
2
3export default function (props) {
4 // Initialized a hook to hold the reference to the title div.
5 const titleRef = useRef();
6
7 useEffect(function () {
8 setTimeout(() => {
9 titleRef.current.textContent = "Updated Text"
10 }, 2000); // Update the content of the element after 2seconds
11 }, []);
12
13 return <div className="container">
14 {/** The reference to the element happens here **/ }
15 <div className="title" ref={titleRef}>Original title</div>
16 </div>
17}
1import React, { useState, useEffect, useRef } from 'react'
2import isDeepEqual from 'fast-deep-equal/react'import { getPlayers } from '../api'
3import Players from '../components/Players'
4
5const Team = ({ team }) => {
6 const [players, setPlayers] = useState([])
7 const teamRef = useRef(team)
8 if (!isDeepEqual(teamRef.current, team)) { teamRef.current = team }
9 useEffect(() => {
10 if (team.active) {
11 getPlayers(team).then(setPlayers)
12 }
13 }, [teamRef.current])
14 return <Players team={team} players={players} />
15}
1function TextInputWithFocusButton() {
2 const inputEl = useRef(null);
3 const onButtonClick = () => {
4 // `current` points to the mounted text input element
5 inputEl.current.focus();
6 };
7 return (
8 <>
9 <input ref={inputEl} type="text" />
10 <button onClick={onButtonClick}>Focus the input</button>
11 </>
12 );
13}
1const refContainer = useRef(initialValue);
2//useRef returns a mutable ref object whose .current property is initialized to the passed argument (initialValue).
3//The returned object will persist for the full lifetime of the component.
1import { useRef } from 'react';
2
3function LogButtonClicks() {
4 const countRef = useRef(0);
5 const handle = () => {
6 countRef.current++; console.log(`Clicked ${countRef.current} times`);
7 };
8
9 console.log('I rendered!');
10
11 return <button onClick={handle}>Click me</button>;
12}