Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
311 views
in Technique[技术] by (71.8m points)

react native - 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 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...