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?
The differences are between:
// 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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With