šŸ“• Build AI Agents using LangGraph.js is now out!

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.

šŸ“– Build a full trivia game app with LangChain

Learn by doing with this FREE ebook! This 35-page guide walks you through every step of building your first fully functional AI-powered app using JavaScript and LangChain.js

šŸ“– Build a full trivia game app with LangChain

Learn by doing with this FREE ebook! This 35-page guide walks you through every step of building your first fully functional AI-powered app using JavaScript and LangChain.js


Leave a Reply

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