šŸŽ Checkout my Learn React by Making a Game course and get 1 month Free on Skillshare!

React keep value between renders without rerendering

If you want to persist and manipulate a value in React between component renders without triggering a new rerendering you may want to take a look at the useRef() hook.

Even dought useRef() is mainly used to store a reference to DOM elements it can be also used to store and update values without extra renderings:

const ref = useRef(0)

<button onClick={()=> ref.current+= 1 } >
        Update ref value
</button>

Let's take the below example that showcases the differences between using useRef() and useState() for storing variables:

The code for this example is pretty straightforward:

const [stateVar, setStateVar] = useState(0)
const refVar = useRef(0)

const incState = () => setStateVar(val => val + 1)
const incRef = () => refVar.current += 1
return (<div>
    <ul>
        <li>āš½ļø useState() var value ={stateVar} </li>
        <li>šŸ„Ž useRef() var value ={refVar.current} </li>
    </ul>
    <button onClick={incState} >
        Increment āš½ļø useState() var - rerenders
    </button>
    <button onClick={incRef}>
        Increment šŸ„Ž useRef() var - will NOT rerender
    </button>
</div>)

If you change the stateVar, the component will re-render, while with the refVar we will keep the value between renders without triggering a new one.

Note that in order to change the refVar value, you will need to change ref.current (and not the refVar itself!)

Also, the šŸ„Ž useRef() var value will not show its real value until a new rerender is triggered by a useState() call.

The full code for the example is here, and the live example is on Github pages.

By the way, if you can also use the useRef() hook to count the real number of renders in a React component.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.


Leave a Reply

Your email address will not be published. Required fields are marked *