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, { useState, useEffect, useRef } from "react";
2import ReactDOM from "react-dom";
3
4import "./styles.css";
5
6function CountMyRenders() {
7 const countRenderRef = useRef(1);
8
9 useEffect(function afterRender() {
10 countRenderRef.current++;
11 });
12
13 return <div>I've rendered {countRenderRef.current} times</div>;
14}
15
16function App() {
17 const [count, setCount] = useState(0);
18 return (
19 <div className="App">
20 <CountMyRenders />
21 <button onClick={() => setCount(count => count + 1)}>
22 Click to re-render
23 </button>
24 </div>
25 );
26}
27
28const rootElement = document.getElementById("root");
29ReactDOM.render(<App />, rootElement);