useRef
/*
A common use case is to access a child imperatively:
*/
function TextInputWithFocusButton() {
const inputEl = useRef(null);
const onButtonClick = () => {
// `current` points to the mounted text input element
inputEl.current.focus();
};
return (
<>
<input ref={inputEl} type="text" />
<button onClick={onButtonClick}>Focus the input</button>
</>
);
}
4.29
7
import React, { useState, useEffect, useRef } from "react";
import ReactDOM from "react-dom";
import "./styles.css";
function CountMyRenders() {
const countRenderRef = useRef(1);
useEffect(function afterRender() {
countRenderRef.current++;
});
return <div>I've rendered {countRenderRef.current} times</div>;
}
function App() {
const [count, setCount] = useState(0);
return (
<div className="App">
<CountMyRenders />
<button onClick={() => setCount(count => count + 1)}>
Click to re-render
</button>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Thank you!
7
0
3.33
3
function TextInputWithFocusButton() {
const inputEl = useRef(null);
const onButtonClick = () => {
// `current` points to the mounted text input element
inputEl.current.focus();
};
return (
<>
<input ref={inputEl} type="text" />
<button onClick={onButtonClick}>Focus the input</button>
</>
);
}
Thank you!
3
0
4
1
import React, { useState, useEffect, useRef } from 'react'
import isDeepEqual from 'fast-deep-equal/react'import { getPlayers } from '../api'
import Players from '../components/Players'
const Team = ({ team }) => {
const [players, setPlayers] = useState([])
const teamRef = useRef(team)
if (!isDeepEqual(teamRef.current, team)) { teamRef.current = team }
useEffect(() => {
if (team.active) {
getPlayers(team).then(setPlayers)
}
}, [teamRef.current])
return <Players team={team} players={players} />
}
Thank you!
1
0
4.33
3
function TextInputWithFocusButton() {
const inputEl = useRef(null);
const onButtonClick = () => {
// `current` points to the mounted text input element
inputEl.current.focus();
};
return (
<>
<input ref={inputEl} type="text" />
<button onClick={onButtonClick}>Focus the input</button>
</>
);
}
Thank you!
3
0
3.75
8
const inputEl = useRef(null);
Thank you!
8
0
Are there any code examples left?
New code examples in category Javascript