Câu hỏi phỏng vấn Reactjs
Câu hỏi

How would you store non-state/instance v...

Câu trả lời

In functional React components, non-state or instance variables can be stored using the useRef hook. This hook is particularly useful for storing values that you want to persist across renders but do not cause a re-render when their values change. Here’s a detailed explanation of how to use useRef for this purpose, along with an example:

Using useRef to Store Non-State Variables

useRef returns a mutable ref object whose .current property is initialized with the passed argument (the initial value). The returned object will persist for the lifetime of the component, much like an instance variable in a class component.

Key Characteristics of useRef:

  • Persistence: The ref object provided by useRef is stable and doesn’t change across re-renders.
  • No Triggering of Re-renders: Updating a ref value using its .current property does not trigger a re-render, making it ideal for values that you want to change without causing a re-render.
  • Direct Mutation: The .current property can be directly mutated, which is similar to how you might mutate instance variables in class components.

Example Usage:

Here’s an example of how useRef can be used to store a non-state variable in a functional component:

import React, { useRef, useEffect } from 'react';

function TimerComponent() {
    const intervalRef = useRef();

    useEffect(() => {
        const id = setInterval(() => {
            console.log('Interval running');
        }, 1000);
        intervalRef.current = id;
        return () => clearInterval(intervalRef.current);
    }, []);

    return <h1>Check the console for interval logs.</h1>;
}

In this example:

  • intervalRef is used to store the interval ID.
  • The interval is set up in the useEffect hook, and its ID is stored in intervalRef.current.
  • When the component unmounts, the interval is cleared using the ID stored in intervalRef.current.

Alternative Approaches

While useRef is a common and straightforward way to handle non-state variables, there are other methods depending on the use case:

  • Local Variables Inside Effects or Functions: If a variable does not need to persist...
senior

senior

Gợi ý câu hỏi phỏng vấn

junior

What happens during the lifecycle of a React component?

senior

When shall we use useReducer hook in ReactJS?

middle

When would you use useRef ?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào