[React] Replacing Instance Variables with the useRef Hook

In addition to storing DOM references, the useRef hook can be used to store values without re-rendering the component.

If you have a class component that stores and manipulates values using instance variables like this:

class YourComponent extends React.Component {
  constructor() {
    this.count = 0;
  }
  onClick(e) {
    this.count++;
  }
  // ...
}

You can simulate this behavior with the useRef hook:

function YourComponent() {
  const countRef = useRef(0);
  function onClick() {
    countRef.current++;   
  }
  // ...
}

In both cases, when the onClick handler is called and either this.count or countRef.current are updated, the component will not re-render.

This can be useful when needing a way to keep track of values for logging or other purposes that don't involve rendering data to the screen.

posted @ 2021-09-10 20:33  Zhentiw  阅读(37)  评论(0编辑  收藏  举报