The useRef Hook

The useRef Hook returns a ref object that can be assigned to a component or element via the ref prop. Refs can be used to deal with references to elements and components in React:

const refContainer = useRef(initialValue)

After assigning the ref to an element or component, the ref can be accessed via refContainer.current. If InitialValue is set, refContainer.current will be set to this value before assignment.

The following example defines an input field that will automatically be focused when rendered:

function AutoFocusField () {
const inputRef = useRef(null)
useEffect(() => inputRef.current.focus(), [])
return <input ref={inputRef} type="text" />
}

It is important to note that mutating the current value of a ref does not cause a re-render. If this is needed, we should use a ref callback using useCallback as follows:

function WidthMeasure () {
const [ width, setWidth ] = useState(0)

const measureRef = useCallback(node => {
if (node !== null) {
setWidth(node.getBoundingClientRect().width)
}
}, [])

return <div ref={measureRef}>I am {Math.round(width)}px wide</div>
}

Refs can be used to access the DOM, but also to keep mutable values around, such as storing references to intervals:

function Timer () {
const intervalRef = useRef(null)

useEffect(() => {
intervalRef.current = setInterval(doSomething, 100)
return () => clearInterval(intervalRef.current)
})

// ...
}

Using refs like in the previous example makes them similar to instance variables in classes, such as this.intervalRef.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.12.172