0 votes
in React Hooks by
Explain the difference between useState and useRef hooks?

1 Answer

0 votes
by
Updating a reference created by useRef doesn't trigger re-rendering, while updating the state (setState) makes the component re-render;

useRef returns an object with a current property holding the actual value. In contrast, useState returns an array with two elements.

useRef‘s current property is mutable, but useState‘s state variable is not.

The reference update is synchronous (the updated reference value is available right away), while the state update is asynchronous (the state variable is updated after re-rendering).

Using useRef - no re-renders

const countRef = useRef(0);

  

const handle = () => {

    countRef.current++;

    console.log(`Clicked ${countRef.current} times`);

};

Using useState - triggers re-render

const [count, setCount] = useState(0);

  

const handle = () => {

    const updatedCount = count + 1;

    console.log(`Clicked ${updatedCount} times`);

    setCount(updatedCount);

};
...