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 } 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, useState } from 'react';
2import ReactDOM from 'react-dom';
3
4function LifecycleDemo() {
5 // It takes a function
6 useEffect(() => {
7 // This gets called after every render, by default
8 // (the first one, and every one after that)
9 console.log('render!');
10
11 // If you want to implement componentWillUnmount,
12 // return a function from here, and React will call
13 // it prior to unmounting.
14 return () => console.log('unmounting...');
15 }, [ // dependencies to watch = leave blank to run once or you will get a stack overflow ]);
16
17 return "I'm a lifecycle demo";
18}
19
20function App() {
21 // Set up a piece of state, just so that we have
22 // a way to trigger a re-render.
23 const [random, setRandom] = useState(Math.random());
24
25 // Set up another piece of state to keep track of
26 // whether the LifecycleDemo is shown or hidden
27 const [mounted, setMounted] = useState(true);
28
29 // This function will change the random number,
30 // and trigger a re-render (in the console,
31 // you'll see a "render!" from LifecycleDemo)
32 const reRender = () => setRandom(Math.random());
33
34 // This function will unmount and re-mount the
35 // LifecycleDemo, so you can see its cleanup function
36 // being called.
37 const toggle = () => setMounted(!mounted);
38
39 return (
40 <>
41 <button onClick={reRender}>Re-render</button>
42 <button onClick={toggle}>Show/Hide LifecycleDemo</button>
43 {mounted && <LifecycleDemo/>}
44 </>
45 );
46}
47
48ReactDOM.render(<App/>, document.querySelector('#root'));
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.