• 카테고리

    질문 & 답변
  • 세부 분야

    프론트엔드

  • 해결 여부

    해결됨

왜 useEffect의 코드가 두번찍히는지 의문입니다.

23.10.11 23:54 작성 조회수 533

0

프론트는 react이고 백엔드는 스프링 부트입니다 .



리액트 소스입니다 .

import "./App.css";
import { useState, useEffect } from "react";

import SERVER_URL from "./config/config";

function App() {
  const [hello, setHello] = useState([]);
  useEffect(() => {
    if (!hello.length) {
      console.log(`서버주소는 ::::::::::::::${SERVER_URL}`);
      fetch(`${SERVER_URL}/api/headers`)
        .then((response) => response.json())
        .then((data) => {
          console.log("데이터:::::::::::", data); // 데이터 출력
          setHello(data); // 데이터를 상태에 설정
        })
        .catch((error) => console.log("Error:", error));
    }
  }, []);
  return (
    <div className="App">
      <div>백엔드에서 가져온 데이터입니다</div>
      <ul>
        {hello.map((item) => (
          <li key={item.id}>{item.name}</li>
        ))}
      </ul>
    </div>
  );
}

export default App;

 

config.js 소스입니다.

const SERVER_URL = "http://localhost:8080";
export default SERVER_URL;

 

백단입니다.

 

package com.service.com.controll;

import java.util.HashMap;
import java.util.List;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import com.service.com.domain.User;
import com.service.com.service.MainService;

import lombok.RequiredArgsConstructor;

@RequiredArgsConstructor
@RestController
public class MainController {

	private final MainService mainService;

	@GetMapping("/api/headers")
	public ResponseEntity<List<User>> getHeaders() {
		List<User> headerList = mainService.findAll();
 		System.out.println(headerList.toString().toString());
 		return ResponseEntity.status(HttpStatus.CREATED).body(headerList);
	}

}
백단 로그입니다 .
[User(id=1, name=a), User(id=2, name=b), User(id=3, name=c), User(id=4, name=d), User(id=5, name=e)]

궁금한 질문입니다 .

서버주소는 ::::::::::::::http://localhost:8080

서버주소는 ::::::::::::::http://localhost:8080

데이터::::::::::: (5) [{…}, {…}, {…}, {…}, {…}]

데이터::::::::::: (5) [{…}, {…}, {…}, {…}, {…}]
왜 2번씩 둘다 찍히는걸까요 ..빈배열 넣었고 처음에만 작동하라고 hello배열의 길이가 없을떄?? useEffect가 작동하라고 코딩했는데 ..궁금합니다.

답변 2

·

답변을 작성해보세요.

2

공부하자님의 프로필

공부하자

2023.10.12

우연히 지나가는 사람입니다.

https://react.dev/reference/react/useEffect#connecting-to-an-external-system

위는 리액트 공식 문서인데, useEffect 부분에서 이 소제목(=> Connecting to an external system)을 찾아보세요. 개발 환경에서는 코드를 두 번 실행해서 버그를 찾는 데 도움이 되도록 한다고 나와 있네요. 백엔드 코드와 프론트엔드 코드 자체는 문제가 없는데도 불구하고 두 번씩 뜨는건 이 이유가 가장 큰 것 같아요. 아마 index.jsx 혹은 tsx 인가? 거기에 App 컴포넌트를 감싼 stric 컴포넌트인가 그거를 제거하면 안 뜰겁니다(참고로 제거 안 하는 걸 권장하고 있고, 제거 안 하더라도 개발자 입장에서는 체감상 개발함에 있어서 차이가 없는게 맞다라고 합니다. 이 또한 공식문서에 나와있는데, 영어를 못해서 의역이 좀 들어갔습니다).

 

지금 보면 서버쪽에 axios로 통신을 하는데 그것도 그러면 2번씩 가거던요 ...

 

공부하자님의 프로필

공부하자

2023.10.14

그래요? 제공 해주신 코드만 보면 제가 봤을 때는 중복 요청 하는 로직이 보이지 않는데, .. 한번 실제 배포 환경에서 어떤지 체크 해보는 것도 좋은 방법일 것 같아요

1

안녕하세요 이정환입니다.

코드 살펴보니 운동하자님의 말씀 처럼 StrictMode로 인해 컴포넌트 자체가 두번 렌더링 되어 useEffect의 콜백함수도 두번 실행됩니다. 그러므로 자연스레 API 요청도 2번 발생하는 것으로 보입니다.

따라서 index.js의 StrictMode를 지워주시고 다시 테스트해보심을 추천드립니다.