score:4

Accepted answer

just store the original value in a ref and compare it to the value provided during render:

const {useref, usestate} = react;

// you can implement the value comparison using your preferred method
function arevaluesequal (value1, value2) {
  return object.is(value1, value2);
}

/**
 * ts:
 * function usevaluechanged <t>(value: t): boolean
 */
function usevaluechanged (value) {
  const originalref = useref(value);
  return !arevaluesequal(originalref.current, value);
}

function example () {
  const rendercountref = useref(0);
  rendercountref.current += 1;
  const [count, setcount] = usestate(0);
  const increment = () => setcount(n => n + 1);
  const didchange = usevaluechanged(count);
  
  return (
    <div>
      <div>render count: {rendercountref.current}</div>
      <div>changed: {didchange ? 'yes' : 'no'}</div>
      <button onclick={increment}>clicks: {count}</button>
    </div>
  );
}

reactdom.render(<example />, document.getelementbyid('root'));
<script src="https://unpkg.com/react@17.0.2/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@17.0.2/umd/react-dom.development.js"></script>

<div id="root"></div>


Related Query

More Query from same tag