I was reading docs from https://www.reactnative.express/react/components/function_components
I do not understand How does the following component work
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: 250 }}>{count}</Text>
My questions:
- What is the use of the function
useEffect()
[What arguments does it take and what does it do with them]
- Why we declared the variable
const id
and why we assigned it setInterval(() => setCount((count) => count + 1), 1000)
- What does
setInterval()
function do. What arguments does it take and what does it do with them. [I am assuming it takes a function to execute and a value which works as a delay for the next execution (I am assuming next execution happens whenever some value in the component changes to re-render the Component.) ] I understand setCount() takes in argument count
and returns count + 1
, which setCount()
uses to update the value of variable count
.
- What does
return () => clearInterval(id)
mean. [As far as I understand return statement calls a arrow function which returns clearInterval(id)
which is then returned as a first argument in useEffect()
function.]. So in essence useEffect
takes an argument returned by clearInterval(id)
where id
was received from setInterval()
as returned value. and Finally --
- What does
clearInterval(id)
means , What does it do with id and what does it return.
- What does the second argument in
useEffect()
mean.
I know if I look in various docs in detail I may find all the answers but that will consume a lot of my time. I need to implement it now.
PLEASE be GENEROUS O Great Coders!! save the enthusiasm I have for this Website, I will surely become a great coder someday but now I need help.
question from:
https://stackoverflow.com/questions/65888828/understanding-the-full-anatomy-of-useeffect-to-set-behavior-of-a-component 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…