React19란

  • React의 최신 버전
  • 메타(구 Facebook) 에 의해 개발
  • 대규모의 동적 웹 애플리케이션을 구축할 때 유용

주요 기능 및 변경사항

  1. Concurrent Mode
    • React 앱의 렌더링 성능을 향상시키기 위해 작업의 우선순위 지정
    • 사용자 인터랙션, 애니메이션 중 중요한 업데이트를 더 빠르게 처리
  2. 서버 컴포넌트
    • 서버 컴포넌트는 서버에서 렌더링
    • 클라이언트로 전송되기 전에 HTML로 변환
    • 페이지 로드 시간 감소
    • 클라이언트의 자바스크립트 부하 감소
  3. 자동 일괄 처리
    • React18에서 도입된 기능 (React19에서 향상)
    • 여러 상태 업데이트를 하나의 렌더링 사이클로 그룹화
  4. Hooks 개선
    • useEffectuseMemo 와 같은 훅의 동작을 최적화
    • 더욱 효율적인 컴포넌트 동작
  5. 개발자 도구의 개선
    • 성능 프로파일링
    • 컴포넌트 트리의 더 나은 시각화
    • 상태 및 속성 변경의 추적 강화

비동기 상태 관리

  • React 18 : 비동기 상태 관리
    - 상태 수동으로 관리
    - useState 와 같은 훅 사용
	
	function UpdateName() {
      const [name, setName] = useState("");
      const [error, setError] = useState(null);
      const [isPending, setIsPending] = useState(false);
      
      const handleSubmit = async() => {
        setIsPending(true);
        try {
          await updateName(name);
          ...   // 성공 시
        } catch (error) {
          setError(error);
        } finally {
          setIsPending(false);
        }
        };
        ...
      };
  • React 19
    - useTransition, useActionState 사용
    - 비동기 작업을 훨씬 깔끔하게 처리
    - pending 상태와 error 처리를 자동으로 관리
    - 코드의 가독성과 유지 관리성을 크게 향상시킴

	function UpdateName() {
      const [name, setName] = useState("");
      const [error, startTransition, isPending] = useActionState();
      
      const handleSubmit = async() => {
        startTransition(async () => {
          try{
            await updateName(name);
            ...
          } catch (error) {
            return error;
            // useActionState는 error를 적절하게 처리
          }
        });
      };
      
      ...
    }

Form 처리

  • React 18
function ChangeNameForm({ onSubmit }) {
  const [name, setName] = useState("");

  const handleSubmit = (event) => {
    event.preventDefault();
    onSubmit(name);
  };

  return (
    <form onSubmit={handleSubmit}>
      <input
        type="text"
        value={name}
        onChange={(event) => setName(event.target.value)}
      />
      <button type="submit">Submit</button>
    </form>
  );
}
  • React 19
    - 비동기 처리 단순화
    - 자동으로 상태 관리

     function ChangeNameForm() {
       const [error, submitAction, isPending] = useActionState(
         async (formData) => {
           const error = await updateName(formData.get("name"));
           if (error) return error;
           redirect("/path");
         }
       );
    
       return (
         <form action={submitAction}>
           <input type="text" name="name" />
           <button type="submit" disabled={isPending}>Submit</button>
           {error && <p>{error}</p>}
         </form>
       );
     }

form의 상태 관리

  • React 18
    - 폼의 제출 상태를 관리하기 위해 useState 사용
    - 폼의 pending 상태 직접 관리 필요

    function LoginForm() {
     const [username, setUsername] = useState("");
     const [password, setPassword] = useState("");
     const [isSubmitting, setIsSubmitting] = useState(false);
    
     const handleSubmit = async (event) => {
       event.preventDefault();
       setIsSubmitting(true);
       await loginUser(username, password);  // 로그인 함수를 비동기로 호출
       setIsSubmitting(false);
     };
    
     return (
       <form onSubmit={handleSubmit}>
         <input
           type="text"
           value={username}
           onChange={(e) => setUsername(e.target.value)}
         />
         <input
           type="password"
           value={password}
           onChange={(e) => setPassword(e.target.value)}
         />
         <button type="submit" disabled={isSubmitting}>Login</button>
       </form>
     );
    }
    
  • React 19
    - useFormStatus 사용
    - 폼의 pending 상태 자동 감지
    - 개발자가 이를 수동으로 설정할 필요 X
    - ContextProvider처럼 부모의 <form> 상태를 읽음

     import { useFormStatus } from 'react-dom';
    
     function LoginForm() {
       const { pending } = useFormStatus();
    
       return (
         <form onSubmit={handleLogin}>
           <input type="text" name="username" />
           <input type="password" name="password" />
           <button type="submit" disabled={pending}>Login</button>
         </form>
       );
     }
    

낙관적 업데이트 처리

  • React 18
    - API 호출 후 문제 발생 시
    - 원래 상태로 롤백하는 로직 수동 구현 필요
function ChangeName({ currentName, onUpdateName }) {
  const [optimisticName, setOptimisticName] = useState(currentName);
  const [isUpdating, setIsUpdating] = useState(false);

  const handleSubmit = async (event) => {
    event.preventDefault();
    const newName = event.target.name.value;  // 폼에서 새 이름을 가져오기
    setOptimisticName(newName);  // 사용자 인터페이스에 즉시 변경을 반영
    setIsUpdating(true);  // 업데이트 진행 중 상태를 설정

    try {
      const updatedName = await updateName(newName);  // API 호출을 통해 이름 업데이트
      onUpdateName(updatedName);  // 부모 컴포넌트에 업데이트를 알리기
      setIsUpdating(false);  // 업데이트 완료 상태 설정
    } catch (error) {
      console.error("Failed to update name:", error);
      setOptimisticName(currentName);  // 오류가 발생하면 원래 이름으로 롤백
      setIsUpdating(false);  // 업데이트 완료 상태 설정
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      <p>Your name is: {optimisticName}</p>
      <p>
        <label>Change Name:</label>
        <input
          type="text"
          name="name"
          value={optimisticName}
          onChange={(e) => setOptimisticName(e.target.value)}
          disabled={isUpdating || currentName !== optimisticName}
        />
        <button type="submit" disabled={isUpdating}>Update</button>
      </p>
    </form>
  );
}

  • React 19
    - useOptimistic 사용
    - 변경사항 자동으로 관리
    - API 요청 성공 여부에 따라 적절히 상태 조정
function ChangeName({currentName, onUpdateName}) {
  const [optimisticName, setOptimisticName] = useOptimistic(currentName);

  const submitAction = async formData => {
    const newName = formData.get("name");
    setOptimisticName(newName);
    const updatedName = await updateName(newName);
    onUpdateName(updatedName);
  };

  return (
    <form action={submitAction}>
      <p>Your name is: {optimisticName}</p>
      <p>
        <label>Change Name:</label>
        <input
          type="text"
          name="name"
          disabled={currentName !== optimisticName}
        />
      </p>
    </form>
  );
}

사용 및 적용

  • React는 빠르게 변화하는 라이브러리
  • 최신 기능들을 학습하고 적용하는 것이 중요
profile
숭실대학교 컴퓨터학부 21

6개의 댓글

comment-user-thumbnail
2024년 5월 29일

스장님 얘 아직 작성 안했어요~

1개의 답글
comment-user-thumbnail
2024년 5월 29일

저기여 얼른 쓰세여~~@

답글 달기
comment-user-thumbnail
2024년 5월 29일

낙관적 업데이트를 이젠 useOptimistic 훅으로 간편하게 구현할 수 있다는게 정말 큰 장점인것 같아요!
점점 공부할게 많아지네요 리액트가 벌써 19라니 ㅎㅎ

1개의 답글

관련 채용 정보

Powered by GraphCDN, the GraphQL CDN