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

149
Vistas
Is useState hook related to hoisting?

I'm fairly new to React.js/javascript and are working on a new project, I would like to be able to manually update my component (due to some 3rd party library limitations) when needed.

After searching I modified a pattern from official site that seems to meets my need by utilizing the useState hook (Though it's not recommended). Below is an extremely simplified component for testing, useRef is needed in my scenario.

What I'm wondering is why the update function can be called properly in useRef, does this have sth to do with hoisting, or it's more of a react thing, such as the execution sequence of hooks are modified under the hood?

https://codesandbox.io/s/useref-usestate-test-0x0hhb?file=/src/App.js

import {useEffect, useRef, useState} from 'react'

export default function App() {
  const testRef = useRef(()=>{
    console.log('testRef called');
    update({});
  })

  const [, update]= useState({});

  useEffect(()=>{
    console.log('updated'); 
  });
  
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>
        <button onClick={()=>testRef.current()}>
          Test
        </button>
      </h2>
    </div>
  );
}
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

It's not about hoisting or React doing anything under the hood – update is a name in the scope that useRef closes over. (It could just as well be a name in another scope, or it could be undefined. Doesn't quite matter.) In fact, as the example below shows, this is just JavaScript and nothing React specific.

There would only be an issue if you called testRef.current() before the const [, update] = ... line (since g is in the Temporal Dead Zone):

function x() {
    const f = () => {
        g();
    };
    f();
    const g = () => console.log("ok");
}

x();

throws

VM471:3 Uncaught ReferenceError: Cannot access 'g' before initialization
    at f (<anonymous>:3:9)
    at x (<anonymous>:5:5)
    at <anonymous>:9:1

but

function x() {
    const f = () => {
        g();
    };
    const g = () => console.log("ok");
    f();
}

x();

just prints

ok

as you'd expect.

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