0

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>
);
7
  • 1
    use useState in this case Commented Jun 23, 2020 at 13:25
  • Why not use useState? Commented Jun 23, 2020 at 13:25
  • I am interacting this variable in third party library listener functions. These libraries loads on page load, and receiving events from javascript listener. Commented Jun 23, 2020 at 13:31
  • 1
    with your approach react dosent know there is a change to be rerender the content Commented Jun 23, 2020 at 13:31
  • To see the new value the component must be updated, this only happens when the state is updated or a passed prop has a new value. For this use useState just the above comments say Commented Jun 23, 2020 at 13:31

2 Answers 2

1

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>
  );
};

Edit exciting-architecture-fu0s6

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.