How would you store non-state/instance variables in functional React components?
How would you store non-state/instance variables in functional React components?
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.Đăng nhập để tham gia thảo luận cùng mọi người.
Chưa có bình luận nào
Hãy là người đầu tiên chia sẻ suy nghĩ của bạn.