Languages

React - why is my component rendering twice?

0 points
Asked by:
Elias999
819

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.

1 answer
0 points
Answered by:
Elias999
819

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.

 

References

  1. Strict Mode – React 
0 comments Add comment
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join