Steps to Create a React App
Step 1: Create a React application using the following command.
npm create-react-app my-app
Step 2: Naviage to the root directory of your folder using the following commad.
cd my-app
Example: Below is an example to show a scnerario where useRef is useful.
Javascript
import { useRef } from 'react' ; export default function Counter() { let ref = useRef(0); function handleClick() { ref.current = ref.current + 1; alert( 'You clicked' + ref.current + 'times' ); } return ( <button onClick={handleClick}> Click me! </button> ); } |
Start your application using the following command.
npm start
Ouput:
How useRef Hook is useful in React ?
Hooks provides a way to useState and other React features in functional components without the need for class components. We can either use built-in hooks or customize and make our own. One of those hooks in useRef. It allows reference to a value that does not require rendering. It can be used to store a mutable value that does not cause a re-render when updated. It can be used to access a DOM element directly.
Table of Content
- Primary Uses of useRef:
- useImperativeHandle
- Conclusion
Contact Us