How would you store non-state/instance v...
How would you store non-state/instance v...
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:
useRef
to Store Non-State VariablesuseRef
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.
useRef
:useRef
is stable and doesn’t change across re-renders..current
property does not trigger a re-render, making it ideal for values that you want to change without causing a re-render..current
property can be directly mutated, which is similar to how you might mutate instance variables in class components.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.useEffect
hook, and its ID is stored in intervalRef.current
.intervalRef.current
.While useRef
is a common and straightforward way to handle non-state variables, there are other methods depending on the use case:
senior
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào