Reputation: 1135
Because this component changes frequently, I decided to use useRef
to store values (for example, a counter). On an event (such as onclick), the log shows that the number did increment by 1 each time the button was clicked, but the value isn't updated on the screen (inside the div). It's showing 0
. What am I missing here?
Intended output: on click button, add()
increases counter
, and display value in <div>
.
const counter = useRef(0);
function add() {
counter.current += 1;
console.log(counter.current); // this shows that the number did increment
}
return (
<div>
<div>{counter.current}</div> {/* this shows '0' */}
<button onClick={() => add()}>Add</button>
</div>
);
Upvotes: 0
Views: 1821
Reputation: 53874
As you stated in the comments:
I am interacting with this variable in third party library listener functions. These libraries loads on page load, and receiving events from javascript listener.
Means that you want to render component on 3rd party reference change, usually you mock a render like so:
const reducer = p => !p;
const App = () => {
const counter = useRef(0);
const [, render] = useReducer(reducer, false);
function add() {
// Some 3rd party ref
counter.current += 1;
// Render and update the UI
render();
}
return (
<div>
<div>{counter.current}</div>
<button onClick={() => add()}>Add</button>
</div>
);
};
Upvotes: 1
Reputation: 21901
read the doc
Keep in mind that useRef doesn’t notify you when its content changes. Mutating the .current property doesn’t cause a re-render. If you want to run some code when React attaches or detaches a ref to a DOM node, you may want to use a callback ref instead.
using the useState
is the best thing in our case
Upvotes: 0