
리액트 19버전의 새로운 점 중 몇가지를 소개하겠습니다. 다른 변경사항들은 공식블로그를 참고하시기 바랍니다.
React v19 blog
Data mutation 과 그에 따른 상태 업데이트를 간소화 하기 위해 도입된 개념이다.
새로 나온 useActionState, useOptimistic 과 같은 훅을 통해 대기 상태, 오류 처리, 낙관적 업데이트를 자동으로 관리할 수 있다.
// 기존 코드
function UpdateName({}) {
const [name, setName] = useState("");
const [error, setError] = useState(null);
const [isPending, setIsPending] = useState(false);
const handleSubmit = async () => {
setIsPending(true);
const error = await updateName(name);
setIsPending(false);
if (error) {
setError(error);
return;
}
redirect("/path");
};
return (
<div>
<input value={name} onChange={(event) => setName(event.target.value)} />
<button onClick={handleSubmit} disabled={isPending}>
Update
</button>
{error && <p>{error}</p>}
</div>
);
}
이전까지는 입력영역마다 상태들을 선언하고 각각 제어해야 했다.
const [error, submitAction, isPending] = useActionState(
async (previousState, newName) => {
const error = await updateName(newName);
if (error) {
// You can return any result of the action.
// Here, we return only the error.
return error;
}
// handle success
return null;
},
null,
);
useActionState 를 사용하면 대기 상태, 에러 처리를 하나의 변수로 처리할 수 있게 해준다.
<form>Actions 와 useFormStatus먼저 <form>, <input>, <button> 요소에 action과 formAction 속성을 추가하여 action이 포함된 form을 자동으로 실행될 수 있게 되었다.
<form action={actionFunction}>
또한 useFormStatus를 사용하면 자식 컴포넌트에서 부모 form의 제출상태, action 함수 등을 조회할 수 있다.
import {useFormStatus} from 'react-dom';
function DesignButton() {
const {pending} = useFormStatus();
return <button type="submit" disabled={pending} />
}
비동기 요청이 진행중일때 상태를 미리 업데이트하는 것을 낙관적 업데이트라고 한다.
useOptimistic 훅은 이것을 더 쉽게 해준다.
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>
);
}
위 코드에서, useOptimistic 은 updateName 요청이 진행중일 때 렌더링을 진행한다. 업데이트가 끝나거나 에러가 발생했을 때, 자동으로 currentName 변수에 반영한다.
RSC(React-Server-Component)는 Next.js 에서 지원하는 server component 유사한 기능을 지원하며 db 쿼리로 직접 데이터를 읽어올 수 있고 SSR(Server-Side-Rendering)과 SSG(Static-Site-Generation)을 가능하게 해준다. 이 기능은 리액트만을 이용해서 앱을 개발하길 원하는 사람에게 많은 도움을 줄 것으로 보인다.
유익한 글 감사합니다🥔🌱