useRef Hook In React Js
Sumit Mishra
Php Architect || Technical Strategist || IT Consultant || Help You In Building IT Team || Project Outsourcing
In React, the useRef hook is used to create a mutable object called a ref. This ref can be attached to a React element and can persist across renders. useRef is commonly used for accessing and interacting with the DOM directly, managing focus, or persisting values without causing re-renders.
Here's a basic example of using the useRef hook in a React functional component:
import React, { useRef, useEffect } from 'react';
const MyComponent = () => {
// Create a ref using the useRef hook
const myInputRef = useRef(null);
useEffect(() => {
// Focus on the input element when the component mounts
myInputRef.current.focus();
}, []);
return (
<div>
<label htmlFor="myInput">Type something: </label>
<input
id="myInput"
type="text"
ref={myInputRef} // Attach the ref to the input element
/>
<p>Value: {myInputRef.current.value}</p>
</div>
);
};
export default MyComponent;
In this example:
Keep in mind that when using useRef, you should not use it to directly manipulate the DOM in a way that bypasses React's state management. It's often used for accessing or interacting with DOM elements imperatively without causing re-renders.
领英推荐
useEffect Hook In React Js
In React, the useEffect hook is used to perform side effects in functional components. Side effects may include data fetching, subscriptions, manually changing the DOM, and other operations that are not pure. The useEffect hook allows you to perform these operations after the component has rendered.
Here's a basic example of using the useEffect hook:
import React, { useState, useEffect } from 'react';
const MyComponent = () => {
// State to hold some data
const [data, setData] = useState(null);
// Effect to fetch data when the component mounts
useEffect(() => {
const fetchData = async () => {
try {
// Simulating a data fetch from an API
const response = await fetch('https://api.example.com/data');
const result = await response.json();
// Update the state with the fetched data
setData(result);
} catch (error) {
console.error('Error fetching data:', error);
}
};
fetchData(); // Call the function to fetch data
// Cleanup function (optional)
return () => {
// Perform cleanup if needed (e.g., cancel subscriptions)
};
}, []); // Empty dependency array means the effect runs only once on mount
return (
<div>
{data ? (
<p>Data: {JSON.stringify(data)}</p>
) : (
<p>Loading...</p>
)}
</div>
);
};
export default MyComponent;
In this example:
The useEffect hook is a powerful tool for managing side effects in React components, helping to keep your code organized and easy to understand.