Whether the array should render four times?

Viewed 31

Hi the following code renders the retrieved array 4 times in the console. It seems to me that in the development version this is normal behavior due to StrictMode. Am I right?

import {useState, useEffect} from 'react';

const ExternalData = () => {

    const [users, setUsers] = useState([])

    useEffect(()=> {
        fetch("https://jsonplaceholder.typicode.com/users")
            .then((res)=>res.json())
            .then((users)=>setUsers(users))
    },[])

    console.log(users);

    return (
        <ul>
            {users.map(item=><li key={item.id}>{item.name}</li>)}
        </ul>
    )
}

export default ExternalData;
1 Answers

First thing, your import should contain react.

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

Yes, it is due to React.StrictMode.

First time when console.log(users); runs, when react renders dom. Output should be [].

Second time when console.log(users); runs, when useEffect runs after first render and calls setUsers(users). This makes the dom rerender, but useEffect will not be called again, as an empty array is passed as a second argument. Output should be (10) [Object, Object, Object, Object, Object, Object, Object, Object, Object, Object].

If you use React.StrictMode, then this whole process happens twice. Initial render runs twice and then rerender after useEffect runs twice, becuase there is the setUser which runs twice in strict mode. Source

Thus, the consol shuld have:

[]
[]
(10) [Object, Object, Object, Object, Object, Object, Object, Object, Object, Object]
(10) [Object, Object, Object, Object, Object, Object, Object, Object, Object, Object]

Example: https://codesandbox.io/s/useeffect-demo-uwywpy?file=/src/App.js

Related