1

Im new in react. I'm Created two file App.js and UseEffect.js I'm Learn about lifecycle in react with function. So When I See in console, that's render multiple time. You can see my picture below.

My Console In Browser

This Is My Code

UseEffect.js

import React, {useState, useEffect} from "react";

function MyFunction(){
console.log('-> Function Init')

const [count, setCount] = useState(0)
const handleCount = () => {
    setCount(prevState => {
        return prevState+1
    })
}

//LifeCycle
useEffect(() => {
    console.log('my first effect')
})

console.log(`-> Start Render (${count})`)
return(
    <div>
            <h1>Function Component</h1>
            <p>
                <button onClick={handleCount}>Count</button>
                {count}
            </p>
    </div>
)}

export default MyFunction

App.Js

import './App.css';
import UseEffect from './components/UseEffect'

function App() {
   return (
      <div className="App">
      <UseEffect />
      </div>
   );
}

export default App;

How do it's work?, I Want it. it's just render one times.

Uletin
  • 31
  • 6
  • You should add [minimal reproducible code](https://stackoverflow.com/help/minimal-reproducible-example), so that people can understand your problem and help you. [see why you shouldn't post image as a code or an error](https://meta.stackoverflow.com/questions/285551/why-not-upload-images-of-code-errors-when-asking-a-question#:~:text=You%20should%20not%20post%20code,order%20to%20reproduce%20the%20problem.) – DecPK Jul 15 '22 at 01:54

2 Answers2

0

Your useEffect call is missing a dependency array. When you want it to run only at the initial render, you need to pass it an empty array as its dependencies.

useEffect(() => {
    console.log('my first effect')
}, [])

For further details, see this question.

Ved
  • 301
  • 3
  • 6
0

Why it renders twice:

It's an intentional feature of the StrictMode. This only happens in development, and helps find accidental side effects put into the render phase. We only do this for components with Hooks because those are more likely to accidentally have side effects in the wrong place.

-gaearon

TLDR: It's a feature not a bug.

Yimin
  • 335
  • 1
  • 8