Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

148
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!