Hi, I'm Jacob. Enjoying devFlipCards? Buy me a coffee

18. How do refs work in React and how do you use them in functional components?

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.

Struggling to find common date to meet with your friends? Try our new tool
commondate.xyz