Refs in React allow you to directly access DOM elements or component instances. Refs can be used to manage focus, select text, trigger animations, or integrate with external libraries.
Using refs in class components:
class MyComponent extends React.Component { constructor(props) { super(props); this.myRef = React.createRef(); } componentDidMount() { this.myRef.current.focus(); } render() { return <input ref={this.myRef} />; } }
Using refs in functional components with the useRef
hook:
import React, { useRef, useEffect } from 'react'; function MyComponent() { const myRef = useRef(null); useEffect(() => { myRef.current.focus(); }, []); return <input ref={myRef} />; }
Refs are useful when you need to directly manipulate DOM elements or access input values in functional components.