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 } from 'react';
2
3function TextInputWithFocusButton() {
4 const inputEl = useRef(null);
5 const onButtonClick = () => {
6 // `current` points to the mounted text input element
7 inputEl.current.focus();
8 };
9 return (
10 <>
11 <input ref={inputEl} type="text" />
12 <button onClick={onButtonClick}>Focus the input</button>
13 </>
14 );
15}
1import React, { useEffect, useRef } from 'react';
2
3const fooComponent = props => {
4 const inputBtnRef = useRef(null);
5 useEffect(() => {
6 //Add the ref action here
7 inputBtnRef.current.focus();
8 });
9
10 return (
11 <div>
12 <input
13 type="text"
14 ref={inputBtnRef}
15 />
16 </div>
17 );
18}
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}