3

When I have a react hook and inside of it I want to define a function in it, would I better use

useEffect(() => {
    //...
    function handler() {}
    //...
}, []);

or the newer const declaration

useEffect(() => {
    //...
    const handler = () => {}
    //...
}, []);

Are both exactly equivalent or are there differences in how Javascript handles these things?

If I define a const, it's only valid within the current scope, while defining a function would be valid elsewhere, is this true?

Does react need the functions accessible in different scopes or are they staying local in the current hook scope?

Krupal Panchal
  • 1,553
  • 2
  • 13
  • 26
user6329530
  • 596
  • 1
  • 7
  • 21

2 Answers2

3

Since THIS is apart of the past by using React Hooks, you can use them both :) it's just syntax sugar es6.

If you want to go deeper on their differences you can use this article: https://www.freecodecamp.org/news/constant-confusion-why-i-still-use-javascript-function-statements-984ece0b72fd/ (there are plenty of more)

BUT IN REACT HOOKS THEY HAVE THE SAME SCOPE

Renaldo Balaj
  • 2,390
  • 11
  • 23
2

React hooks you can only use in pure components, means functions. So most of things you do there is just working as would you work with just some js function, no much difference really. In hooks themselves not all things possible, like one time I tried to make useEffect hook callback to be async function and get warning to run async function inside of it instead.

Inside pure component, that function, you not really need any this, so as Renaldo Balaj said, there is no difference wether use usual or arrow function.

Ivan Cherviakov
  • 528
  • 2
  • 12