useRef
Allows you to create a mutable reference to a value or a DOM element that persists across re-renders.
Useful for:
- Accessing and manipulating DOM elements directly: You can create a that points to a specific element in the DOM, enabling you to interact with it using imperative calls instead of relying solely on the declarative approach of rendering components.
- Storing persistent values:
useRef
provides a way to store values that need to remain the same during re-renders. This is beneficial for scenarios like tracking previous values, managing timers, or storing references to external libraries. - Working with values that don't trigger re-renders: If a value doesn't affect the component's rendering,
useRef
is a good choice to avoid unnecessary re-renders due to state updates.
Example
import { useRef } from "kaioken"
function App() {
const inputRef = useRef(null) // Create a ref for the input element
const handleClick = () => {
inputRef.current?.focus() // Access and focus the input element using the ref
}
return (
<div>
<input ref={inputRef} type="text" />
<button onclick={handleClick}>Focus Input</button>
</div>
)
}