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>
);
}
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.