×
☰ See All Chapters

React useRef Hook

React is alerting you that variables are not stable. Whenever there is a rerender, it will recalculate the variable. Normally, this will ensure up-to-date information. In this case, you are relying on that variable to persist. The solution is another Hook called useRef. The useRef Hook will preserve a variable for the lifetime of the component. The only trick is to get the value you need to use the .current property. To preserve the value over time, store it in a useRef Hook and keep the mutable value in the '.current' property. useRef() only returns one item. It returns an Object called current.  const count = useRef(0); is equivalent to const count = {current: 0};

If we tried to count how many times our application renders using the useState Hook, we would be caught in an infinite loop since this Hook itself causes a re-render. To avoid this, we can use the useRef Hook as given in below example:

demo.component.js

 

import { useState, useEffect, useRef } from "react";

 

function DemoComponent() {

  const [inputValue, setInputValue] = useState("");

  const count = useRef(0);

 

  useEffect(() => {

    count.current = count.current + 1;

  });

 

  return (

    <>

      <input

        type="text"

        value={inputValue}

        onChange={(e) => setInputValue(e.target.value)}

      />

      <h1>Render Count: {count.current}</h1>

    </>

  );

}

export default DemoComponent;

index.js

import React from 'react';

import ReactDOM from 'react-dom';

import './index.css';

import DemoComponent from './components/demo.component';

import reportWebVitals from './reportWebVitals';

 

ReactDOM.render(

  <React.StrictMode>

    <DemoComponent></DemoComponent>

  </React.StrictMode>,

  document.getElementById('root')

);

 

reportWebVitals();

react-useref-hook-0
 
react-useref-hook-1
 

All Chapters
Author