skip to Main Content

Look at this below code

const Test = () => {
  useEffect(() => {
    axios.get(`test-messages`).then((result) => {
      console.log("test");
    });
  });

  return <h1>Test</h1>;
};

export default Test;

Problem is that all the times react send 4 request. 2 request (2 returns data from the server). Do you know where problem is?

2

Answers


  1. try to add add [] as dependency

    const Test = () => {
     useEffect(() => {
        axios.get(`test-messages`).then((result) => {
          console.log("test");
        });
      }, []);
    
      return <h1>Test</h1>;
    };
    
    export default Test;
    

    axios.get will be triggered once when component will be rendered.

    u should know how useEffect is working please check examples or read docs. it is very important
    https://react.dev/reference/react/useEffect

    Login or Signup to reply.
  2. I think you should check your ‘index.js’ file, the <React.StrictMode> runs your code twice, so it might come from there. (I’ve got the same issue and that’s how I solved this problem)

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