The following code works as expected and displays the number 1:
"use client";
import { useEffect, useState } from "react";
export function StateTest() {
useEffect(() => {
setX(1);
});
const [x, setX] = useState(0);
return <div className="w-64 bg-black p-8 text-center text-white">{x}</div>;
}
How can this be when the following code fails to execute in node or in the browser:
function callbackLogger(callback) {
console.log(callback());
}
function main() {
callbackLogger(() => {
return helloWorld();
});
const helloWorld = () => {
return "Hello World!";
};
}
main();
When run this in the firefox terminal it produces the error:
Uncaught ReferenceError: can't access lexical declaration 'helloWorld' before initialization
How can this be? Is React reorganizing my code? Is there something magical about react dispatches?
1
If you re-define helloWorld
using the function keyword instead of const, it works.
function callbackLogger(callback) {
console.log(callback());
}
function main() {
callbackLogger(() => {
return helloWorld();
});
function helloWorld() {
return "Hello World!";
};
}
main();
The short explanation for this is Declaration Hoisting.
The MDN Website goes into this in a lot of detail.
Hoisting allows your functions and classes to be accessed before they are declared. That’s why the function declared with the function
keyword did not give an error.
However, this does not work with function expressions.
1