1

I have this in my code:

const [dimensions, setDimensions] = useState(getDimensions())

const getDimensions = () => {
   // stuff
}

The function hasn't be declarated when I call it, so I get an error. But, if I declare it as a traditional function no error is going on.

const [dimensions, setDimensions] = useState(getDimensions())

function getDimensions() {
   // stuff
}

Is there any way to do this with an arrow function?

Victor Molina
  • 2,353
  • 2
  • 19
  • 49

2 Answers2

2

This is because with the arrow function example you are declaring a function expression. Function expressions are not hoisted. If you need to use an arrow function, you would need to declare it before use.

aprouja1
  • 1,800
  • 8
  • 17
  • "*you are declaring a function expression*" - to particularise, you are declaring a `const`, and initialise it with an arbitrary expression (which in this case happens to be an arrow function literal). And [initialisers are not hoisted](https://stackoverflow.com/a/31222689/1048572). – Bergi Aug 01 '20 at 17:41
  • @Bergi so it stands that if you initialized an arrow function with a `var` then it would be hoisted and called w/o error? – Hyetigran Aug 01 '20 at 17:44
  • 2
    @Hyetigran No, `var` initialisers are not hoisted either, but `var`s are implicitly initialised with `undefined` so when trying to call it you'll just get a different error. – Bergi Aug 01 '20 at 17:47
0

I can't speak to why arrow and traditional functions behave differently.

But if you wanted to use an arrow function then you can update your code to set an initial state and only call getDimensions once component is mounted with useEffect.

Example:

const [dimensions, setDimensions] = useState({})

const getDimensions = () => {
   // stuff
}
useEffect(()=> {
  getDimensions()
}, [])
Hyetigran
  • 1,150
  • 3
  • 11
  • 29