Understanding the full anatomy of useEffect() to set behavior of a Component
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 itsetInterval(() => 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 argumentcount
and returnscount + 1
, whichsetCount()
uses to update the value of variablecount
. - What does
return () => clearInterval(id)
mean. [As far as I understand return statement calls a arrow function which returnsclearInterval(id)
which is then returned as a first argument inuseEffect()
function.]. So in essenceuseEffect
takes an argument returned byclearInterval(id)
whereid
was received fromsetInterval()
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.