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

Time:12-14

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

CodePudding user response:

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

  • Related