Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between useState(function_name), useState(function_name()), useState(()=>function_name()) and useState(()=>function_name)?

The function createHiveBackground returns an array of objects that I want to assign to a state. Later in my application I'm going to use setHive to change some values of the array. What is the difference between these?

const [hive, setHive] = React.useState(createHiveBackground);
const [hive, setHive] = React.useState(createHiveBackground());
const [hive, setHive] = React.useState(()=>createHiveBackground);
const [hive, setHive] = React.useState(()=>createHiveBackground());

If I use useState(createHiveBackground) it seems to work properly.

If I use useState(createHiveBackground()) each time I change a value with setHive the function is called again.

If I use useState(()=>createHiveBackground) TypeError: hive.map is not a function (seems like the function is not being executed).

If I use React.useState(()=>createHiveBackground()); it seems to work properly.

Can some clarify what is the difference between all these options and what is the best for my case?

like image 977
devamat Avatar asked Mar 13 '26 14:03

devamat


1 Answers

The differences are between:

  • Value type: Function/Array (Function's return type).
  • Initial type: Normal/Lazy
// Lazy assign the return value of the function
// Both are equivalent as First-class functions (check the reference)
const [hive, setHive] = React.useState(createHiveBackground);
const [hive, setHive] = React.useState(() => createHiveBackground());

// Assign the return value from the function
const [hive, setHive] = React.useState(createHiveBackground());

// Lazy assign the function
const [hive, setHive] = React.useState(() => createHiveBackground);

References:

  • useState Hook
  • Lazy initial state
  • First Class Function
like image 157
Dennis Vash Avatar answered Mar 15 '26 05:03

Dennis Vash



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!