0

this code:

const TooMany = () => {
    const [count, setCount] = useState(0);

    const foo = (param) => {
        console.log("Called twice")
        return param;
    }

    let bar = foo(1);

    return (
        <div>
            TEST
        </div>
    )
}

runs foo twice. Why? My guess was that the second one is triggered by useState but when I created another useState it did not increase amount of the foo calls. So I am confused...

Jacek Wojcik
  • 1,223
  • 2
  • 19
  • 33
  • I would use `foo(1)` function call in `useEffect` hook instead. – norbitrial May 31 '20 at 15:22
  • 3
    There is nothing wrong with you code, at least obviously. If you created the application with `create-react-app` it is likely using [Strict Mode](https://reactjs.org/docs/strict-mode.html). In development mode only there will be additional renders to attempt to highlight potential issues in your application. This will not happen in production mode. – Alexander Staroselsky May 31 '20 at 15:29
  • 2
    Check this: https://stackoverflow.com/questions/60825649/why-my-simple-react-component-print-console-twice/60825885#60825885 its because of React.StrictMode – Yash Joshi May 31 '20 at 15:34
  • 1
    As commented per others, this is due to strict mode. See this discussion on github https://github.com/facebook/react/issues/15074 – Anthony Garcia-Labiad May 31 '20 at 15:43

1 Answers1

-1

In React js Render method called every property change but not every other method, like as componentDidmount, WillMount, etc. in update React use React Hooks with the functional component. just one function use to solve it "useEffect" here the snippet or visite the link Codesandbox

const TooMany = () => {
    const [count, setCount] = useState(0);

    const foo = (param) => {
        console.log("Called twice")
        return param;
    }

    useEffect(()=>{
       let bar = foo(1);
    },[])

    return (
        <div>
            TEST
        </div>
    )
}
Md. Abu Sayed
  • 2,396
  • 2
  • 18
  • 26