Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

146
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda