useRef vs useState?
Try code in the playgroundUnderstand the concept
useState stores a value that participates in the UI, while useRef stores a stable mutable container whose changes do not request rendering. A ref is useful for an imperative handle such as a DOM node or timer ID. It should not replace state for information that the screen must show when it changes.
Important ideas
-
State changes can trigger rendering; changing
ref.currentdoes not. -
Use refs for DOM nodes, timer IDs or mutable values not shown in the UI.
-
Use state when the user should see a value change.
-
Avoid reading or writing ordinary mutable refs during rendering to drive unpredictable UI; keep render output based on props and state.
Can you explain it without the notes?
useRef vs useState?
Use your own words. Explain an example and one limitation before checking the explanation.
Check your explanation
useState stores a value that participates in the UI, while useRef stores a stable mutable container whose changes do not request rendering. A ref is useful for an imperative handle such as a DOM node or timer ID. It should not replace state for information that the screen must show when it changes.
Turn this concept into a clear answer.
- Ask whether changing the value should update the screen. That usually decides between state and a ref.
Adapted from 06_REACT_NEXTJS.md · “useRef vs useState?”. Examples are study fragments; framework behavior can depend on your version.