Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

273
Vistas
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

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

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

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.

about 4 years ago · Juan Pablo Isaza Denunciar

0

You should use a state variable for previous instead of just a plain variable. Otherwise, if not stateful, the variable will always reset on re-render.

Also there's not need for updating the innerHTML via ref in this case since the variable is already being rendered.

//...
const [previous, setPrevious] = useState(0)

function increment(){
    setPrevious(previous + 1)
}
//...

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda