useRef is a structure that allows us to keep a "mutable" variable within a component without triggering the component to be rendered again.
If we had performed the above example with useState, after clicking the button once, the component would be rendered again and "Clicks: 1" would appear on the screen. Since we keep the variable with useRef, the first value "Clicks: 0" will appear, but the "count" value will be 1 in memory.
What is the difference between useRef and useState?
When a variable changes, useState triggers the component to be rendered again. useRef does not trigger the component to be rendered again.
Top comments (0)