DEV Community

Discussion on: React's useEffect and useRef Explained for Mortals

Collapse
 
jeromedeleon profile image
Jerome De Leon • Edited

I would probably do something like this:

function Counter() {
  const [count, setCount] = React.useState(0);
  const [,forceUpdate] = React.useState({}); 
  const countRef = React.useRef(0);

  return (
    <div>
      <p>State Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>
        Increment State Count
      </button>
      <p>Ref Count: {countRef.current}</p>
      <button onClick={() => {
        countRef.current = countRef.current + 1;
        forceUpdate({});
      }>
        Increment Ref Count
      </button>
    </div>
  )
}

just in case someone wants a workaround of ref in React. I personally prefer using ref.