HomeReact Hooks
React Custom Hooks
Array Methods
Reference useRef
- Example: Reference elements within the dom.
- Example: Great for hold previous state of state.
- Example: Ref do not cause the component to update when changed.
- Import: DO NOT destructure the setting of useRef, because it returns a single object containing 'current'.
WDS Video on this Hook
import React, { useEffect, useRef, useState } from "react";
function ExampleUseRef() {
const [something, setSomething] = useState(null);
const inputRef = useRef("");
const prevSomething = useRef("");
function example() {
inputRef.current.focus();
}
useEffect(() => {
prevSomething.current = something;
}, [something]);
return (
<Stack alignItems={"center"} sx={{ width: "100%", maxWidth: "40dvw", margin: 2, backgroundColor: "lightblue", padding: 7, borderRadius: 15 }}>
<input ref={inputRef} type="text" onChange={(e) => setSomething(e.target.value)} />
<Typography variant="h6" sx={{ marginBottom: 5 }}>
Example - {something} and previous state was: {prevSomething.current}
</Typography>
<Stack direction={"row"} alignItems={"center"} gap={5}>
<Button variant="contained" onClick={() => example()}>
Example
</Button>
</Stack>
</Stack>
)
}