useRef with variables code example
Example 1: useRef
function TextInputWithFocusButton() {
const inputEl = useRef(null);
const onButtonClick = () => {
inputEl.current.focus();
};
return (
<>
<input ref={inputEl} type="text" />
<button onClick={onButtonClick}>Focus the input</button>
</>
);
}
Example 2: useRef
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} />
}