Skip to content

Instantly share code, notes, and snippets.

@Goloburda
Last active January 4, 2020 13:19
Show Gist options
  • Save Goloburda/98e85c020bf88632e1d0f485538259d9 to your computer and use it in GitHub Desktop.
Save Goloburda/98e85c020bf88632e1d0f485538259d9 to your computer and use it in GitHub Desktop.
React functional component function hoisting.
const App = () => {
// Ugly. I always want to declear hooks at the top.
// But I can't swap getDefaultValue and useState (error getDefaultValue is't a function),
// because I use function assigmnet and in that way function does't hoisting.
const getDefaultValue = () => {
return "Default value";
};
const [title, setTitle] = useState(getDefaultValue());
// Correct one. Function declarations hoist the function definitions.
function setDefaultValue() {
return "Default declaration";
}
return <div>{title}</div>;
}
//Note
const App = () => {
const handleInput = (event) => {
/* logUserInput is used before declared
But there is no error,
because code inside handleInput function
executed only after user will type something
*/
logUserInput(event.target.value)
}
// Error => logUserInput is not a function
handleInput({target: {value: "Simulate event call"}})
const logUserInput = (input) => {
console.log(input)
}
// No error
handleInput({target: {value: "Simulate event call"}})
return <input onChange={handleInput} />;
}
// Just for fun
const App = () => {
const handleInput = event => {
logUserInput(event.target.value);
};
return <input onChange={handleInput} />;
// logUserInput hoist and everything works as expected
function logUserInput(input) {
console.log(input);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment