Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Preventing variable from being reset when using state – React

Let’s say we have a variable that should not be changed with react rendering. Is this possible?, without me having to use a context or raise the variable up a hierarchy in the components.

import React, {useState,useMemo,useRef} from 'react'

const Component=()=>{

   const [state,setState] = useState(false)
   const ref = useRef(null)

   let previous = 0

   function increment(){
       previous++
       ref.current.innerHTML = `VARIABLE: ${previous}`
   }

   return (
       <div>
           <div ref={ref}>VARIABLE: {previous}</div>
           <div>
               <button onClick={increment}>Incremente Let</button>
               <button onClick={()=>{setState(!state)}}>Change State</button>
           </div>
       </div>
    )
  }

 export default Component

enter image description here

I know I can use state as well, but let’s see that updating the variable will trigger new renders, but the variable doesn’t need to be rendered, so why a state. This code is just an example

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

This example is a demonstration of the problem, not an actual implementation

>Solution :

You could use useRef. The value will persist rerenders and changes will not trigger rerenders.

const previous = useRef(0);

function increment(){
    previous.current++;
}

Since modifying it won’t trigger a rerender, you want to make sure you’re not rendering the value.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading