React - why is my component rendering twice?
Why is my component rendering twice?
I'm using useEffect() with axios to fetch some data inside the following component:
const Items = () => {
const [items, setItems] = useState([]);
useEffect(() => {
axios
.get('https://some-api.com/items/')
.then((res) => console.log(res.data))
.catch((err) => console.log(err));
}, []);
return (
<div className='items'>
{items.map((item) => (
<Item key={item.id} name={item.name}></Item >
))}
</div>
);
};
Now, when I npm start my application, the console shows two messages from the console.log(res.data).
Why is that so? I'm using empty array of dependencies for the useEffect() hook so it should be displayed only once on the Items component mount.
The reason for that may be running an app in strict mode.
Go to index.js file in your project and comment strict mode tag, the component should render only once.
From the documentation:
Strict mode can’t automatically detect side effects for you, but it can help you spot them by making them a little more deterministic. This is done by intentionally double-invoking the following functions:
...
Note:
This only applies to development mode. Lifecycles will not be double-invoked in production mode.