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, { useRef, useEffect } from 'react';
2
3function CountMyRenders() {
4 const countRenderRef = useRef(1);
5
6 useEffect(function afterRender() {
7 countRenderRef.current++; });
8
9 return (
10 <div>I've rendered {countRenderRef.current} times</div>
11 );
12}