useRef Hook In React Js

useRef Hook In React Js

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:

  • We create a ref called myInputRef using useRef(null).
  • We attach this ref to the input element using the ref attribute.
  • In the useEffect hook, we use myInputRef.current.focus() to focus on the input element when the component mounts.
  • The current value of the input can be accessed using myInputRef.current.value.

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:

  • We initialize a state variable data using the useState hook to hold some data.
  • We use the useEffect hook to fetch data when the component mounts. The fetchData function is defined inside the effect and is called immediately.
  • The effect has an empty dependency array ([]), which means it will run only once when the component mounts. If you provide dependencies, the effect will run whenever any of those dependencies change.
  • The cleanup function inside the useEffect can be used for cleanup tasks like unsubscribing from subscriptions to prevent memory leaks.

The useEffect hook is a powerful tool for managing side effects in React components, helping to keep your code organized and easy to understand.

要查看或添加评论,请登录

Sumit Mishra的更多文章

  • CSS Specificity

    CSS Specificity

    CSS specificity is a set of rules used to determine which styles are applied to an element when multiple conflicting…

  • Install & Run Typescript

    Install & Run Typescript

    To compile TypeScript code into JavaScript, you need to have the TypeScript compiler () installed. You can install it…

  • Php 8 New Concepts

    Php 8 New Concepts

    PHP 8 introduced several new features and improvements. Here are some of the key concepts with examples: Named…

  • Children In React Js

    Children In React Js

    In React.js, handling children is a fundamental aspect of building components.

  • Destructuring In JavaScript

    Destructuring In JavaScript

    Destructuring is a feature in JavaScript that allows you to extract values from arrays or properties from objects and…

  • Abstract Data Type In Detail

    Abstract Data Type In Detail

    An Abstract Data Type (ADT) is a high-level description of a set of operations that can be performed on a particular…

  • API resources In Laravel

    API resources In Laravel

    In Laravel, API resources provide a convenient way to transform and format your Eloquent models and collections into a…

  • Flux Pattern In React Js With Example

    Flux Pattern In React Js With Example

    Install Dependencies: You'll need to install package. You can install it using npm or yarn: or Implement Flux…

  • Rules of Hooks In React Js

    Rules of Hooks In React Js

    In React, hooks are functions that allow you to use state and other React features in functional components. The most…

  • What is Cron Jobs. How to Implement Cron Jobs in Php

    What is Cron Jobs. How to Implement Cron Jobs in Php

    Cron jobs in PHP are scheduled tasks that run automatically at predefined intervals on a Unix-based system. These tasks…

社区洞察

其他会员也浏览了