Reputation: 1662
import React, { useEffect, useState } from 'react'
import { Text } from 'react-native'
export default function Counter() {
const [count, setCount] = useState(0)
useEffect(() => {
const id = setInterval(() => setCount((count) => count + 1), 1000)
return () => clearInterval(id)
}, [])
return <Text style={{ fontSize: 120 }}>{count}</Text>
}
so how does the count and setCount get values from useState(0)
const [count, setCount] = useState(0)
can you walk me through this confusion, as if I'm five.
Upvotes: 2
Views: 991
Reputation: 181
After every 1000 ms (1 sec)
useEffect(() => {
const id = setInterval(() => setCount((count) => count + 1), 1000)
return () => clearInterval(id)
}, [])
this function called and update the value of count.
setInterval function sets the time interval when it called again automatically
I hope you will clear about that.
Upvotes: -1
Reputation: 131
The useState hook simply returns an array with two values: the first one is the value that you will want to use in your component, and the second one is the function that you can invoke to change the value. The useState hook takes an argument that allows you to set the initial value.
For further reading, please refer to the React documentation: https://reactjs.org/docs/hooks-state.html
The bracket notation simply destructures the array that the useState hook returns, so that you can easily access its values in your component.
Upvotes: 3
Reputation: 11822
The function useState
returns an array wrapping two values (the stateful value and the setter). This is done so that a single function call can return two values at once (which is not supported by JavaScript as a language - other languages do support such things though).
Example:
function neighbors (num) {
return [num - 1, num + 1]
}
const [seven, nine] = neighbors(8)
Upvotes: 2