skip to Main Content

I write a React code, but it call fetch twice when I load page to browser. My question is why? How can I reduce to one call?

The code is the following:

import { useEffect, useState } from "react";
import { useCookies } from "react-cookie";

const UserInfo = () => {
    const [cookies, setCookie, removeCookie] = useCookies(['x-auth-token']);
    const [userInfo, setUserInfo] = useState({ _id: 0, name: '', email: '', password: '' });
    useEffect(() => {
        fetch(`http://localhost:8080/api/users/me`, {
            method: 'GET',
            mode: 'cors',
            headers: {
                'Content-Type': 'application/json',
                'x-auth-token': cookies["x-auth-token"],
            },
            cache: 'no-cache'
        }).then((response) => response.json()).then(data => {
            console.log(JSON.stringify(data));
            setUserInfo(data);
        }).catch((e) => {
            console.log(e);
        });
    }, []);


    return (
        <div className="App">
            <h1>Home</h1>
            <p>Hello {userInfo.name} from {userInfo.email}!</p>
        </div>
    );
}

export default UserInfo;

The App.tsx is here:

import "primereact/resources/themes/lara-light-indigo/theme.css";
import "primereact/resources/primereact.min.css";
import "primeicons/primeicons.css";
import "primeflex/primeflex.css";

import React from 'react';
import { BrowserRouter, Route, Routes } from 'react-router-dom';
import Register from './pages/register';
import Login from './pages/login';
import Home from './pages/home';
import UserInfo from "./pages/userinfo";

function App() {
  return (
    <React.StrictMode>
      <div className="App">
        <BrowserRouter>
          <Routes>
            <Route path='/register' element={<Register />} />
            <Route path="/login" element={<Login />} />
            <Route path="/user" element={<UserInfo />} />
            <Route path="/" element={<Home />} />
          </Routes>
        </BrowserRouter>
      </div>
    </React.StrictMode>
  );
}

export default App;

I think my question is not enought length, because I get comment about it is mostly code then question. So I write some words here. Please help me. Writesonic can’t tell the true.

3

Answers


  1. The fetch might be called twice as the component is rendered twice . if you are rendering the component inside another component that is being re-rendered, such as a parent component that updates its state.

    you could try to use

    React.memo (which is a higher-order component)

    If you want the useEffect to run once when component is being rendered , try something like this :

    change

    export default UserInfo;
    

    to

    export default React.memo(UserInfo);
    
    Login or Signup to reply.
  2. It happening due to react in strict mode in v18
    you can use below statement if you want to fetch once

    if (!userInfo) {
      const data = /*  api call */
      setUserInfo(data);
    }
    

    reusable state link

    Login or Signup to reply.
  3. In development, when strict mode is enabled, components mount twice, so the useEffect hook runs twice. It shouldn’t happen in production.
    https://upmostly.com/tutorials/why-is-my-useeffect-hook-running-twice-in-react

    You can disable strict mode by removing

    <React.StrictMode>
    </React.StrictMode>
    

    from your App component

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search