I am learning and practicing hooks useState in react js. For example, when declaring a state variable like this,
const [votes, setVotes] = useState(0) I know that the 0 value in useState() means that votes is initialized with starting value of 0. However, advancing a little bit, like this,
const [votes, setVotes] = useState(() => Array(fruits.length).fill(0)) Given an array,
const fruits = ["kiwi", "banana", "mango", "apple", "durian"] I am a little confused with the Array in the second state variable wrapping fruits.length, why do we have to wrap it with Array ? fruits is already an array. And just to make sure that I understand, the .fill(0) means that we will initialize every element in the array fruit with 0? Am I right ? To give a context, I have an array fruits and two buttons, one is to vote, and the other is to select randomly the next fruit. Every time I vote, the vote will increase and when I click the other button, random fruits will be displayed and the vote will be 0 for fruits that haven't got voted. This is the vote button code,
const handleVotes = () => { setVotes((votes) => votes.map((vote, index) => index === selected ? vote + 1 : vote) ) }
fruits.fill(0)it will overwrite all values infruitswith0for each value.Array(fruits.length).fill(0)makes a new array filled with0s, matching the length offruits. run it in a console to see for yourself. also note() => ...precedes the state, this is a lazy state initializer and runs only once when the component is initialized. this is important otherwiseArray(fruits.length).fill(0)would be evaluated during each render, even though the value would be discarded.