Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

useRef underline current is changed but it will not paint to dom

Why it is not re-rendering the component even though current is changed. I know it can be done with useState.

 const onDecrement = () => {
    counter.current -= 1;
  };

  const onIncrement = () => {
    counter.current += 1;
  };

  const onReset = () => {
    counter.current = 0;
  };

  useEffect(() => {
   // It should trigger this
    console.log('re-render'); 
  }, [counter.current]);

Playground: https://stackblitz.com/edit/react-ts-xtamop?file=useFetch.tsx,App.tsx

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

useRef are used to avoid re-render as opposed to useState which causes re-render when change happens.

As for your context, you can assign the ref to the div element and use the inntertext to assign values

  const counter = useRef<HTMLDivElement>(null);

  const onDecrement = () => {
    counter.current.innerText = `${Number(counter.current.innerText) - 1}`;
  };

  const onIncrement = () => {
    counter.current.innerText = `${Number(counter.current.innerText) + 1}`;
  };

  const onReset = () => {
    counter.current.innerText = '0';
  };


 // only executes in the initial render
  useEffect(() => {
    console.log('re-render');
    counter.current.innerText = '0';
  }, [counter.current]);

  return (
    <div>
      <button onClick={onDecrement}>-</button>
      <div
        ref={counter}
        style={{ display: 'inline-block', margin: '0 10px' }}
      ></div>
      <button onClick={onIncrement}>+</button>
      <div style={{ marginTop: '10px' }}>
        <button onClick={onReset}>Reset</button>
      </div>
    </div>

Demo

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading