>  기사  >  웹 프론트엔드  >  React와 React(RC): 주요 차이점 및 예제가 포함된 마이그레이션 팁

React와 React(RC): 주요 차이점 및 예제가 포함된 마이그레이션 팁

WBOY
WBOY원래의
2024-09-03 14:21:29954검색

React vs React (RC): Key Differences and Migration Tips with Examples

사용자 인터페이스 구축에 널리 사용되는 JavaScript 라이브러리인 React는 새로운 릴리스가 나올 때마다 계속 발전하고 있습니다. 이 블로그 게시물에서는 React 18과 곧 출시될 React 19(현재 릴리스 후보 단계)의 주요 차이점을 살펴보고, 새로운 기능의 예를 제공하며, Vite와 함께 React를 사용하는 개발자를 위한 마이그레이션 팁을 제공할 것입니다.

목차

  1. 소개
  2. React 19 현황
  3. 예제와의 주요 차이점
    • 향상된 서버측 렌더링
    • 향상된 동시 렌더링
    • 새로운 후크 및 API
    • 성능 최적화
  4. 마이그레이션 팁
  5. Vite와 함께 React 19 RC 사용하기
  6. 결론

소개

React 18에는 자동 일괄 처리, 동시 렌더링을 위한 새로운 API, 전환 등 중요한 변경 사항이 도입되었습니다. React 19는 아직 개발 단계에 있지만 이러한 기반을 바탕으로 추가 개선 사항과 새로운 기능을 구축하는 것을 목표로 합니다.

React 19 현황

2024년 9월 현재 React 19는 RC(Release Candidate) 단계에 있습니다. 기능이 완벽하고 테스트할 준비가 되어 있지만 아직 프로덕션 용도로 권장되지는 않습니다. 기능과 API는 최종 출시 전에도 변경될 수 있습니다.

예제와의 주요 차이점

해당되는 경우 React 18과의 예와 비교를 통해 React 19에서 예상되는 주요 개선 사항과 새로운 기능을 자세히 살펴보겠습니다.

향상된 서버 측 렌더링

  1. 향상된 스트리밍 SSR

React 19는 스트리밍 SSR을 더욱 최적화하는 것을 목표로 합니다. API는 React 18과 유사하게 유지될 수 있지만 성능 향상은 눈에 띌 것입니다.

예(React 18과 19 모두 유사):

// server.js
import { renderToPipeableStream } from 'react-dom/server';

app.get('/', (req, res) => {
  const { pipe } = renderToPipeableStream(<App />, {
    bootstrapScripts: ['/client.js'],
    onShellReady() {
      res.statusCode = 200;
      res.setHeader('Content-type', 'text/html');
      pipe(res);
    },
  });
});
  1. 정제된 선택적 수분 공급

React 19는 React 18에서 도입된 선택적 수화작용을 개선할 것으로 예상됩니다.

React 19의 예(구문은 React 18과 유사하지만 동작이 개선됨):

import { Suspense } from 'react';

function App() {
  return (
    <Suspense fallback={<Loading />}>
      <MainContent />
      <Suspense fallback={<SidebarLoading />}>
        <Sidebar />
      </Suspense>
    </Suspense>
  );
}

이 예에서 React 19는 사이드바가 로드되는 동안 MainContent 구성 요소의 우선 순위를 지정하여 보다 원활한 수화를 제공할 수 있습니다.

  1. 서버 구성요소

React 19에는 서버 구성 요소의 보다 안정적인 구현이 포함될 것으로 예상됩니다.

React 19의 서버 구성 요소 예:

// Note: This syntax is speculative and may change
'use server';

import { db } from './database';

async function UserProfile({ userId }) {
  const user = await db.user.findUnique({ where: { id: userId } });
  return <div>{user.name}</div>;
}

export default UserProfile;

이 예에서 UserProfile 구성 요소는 서버에서 실행되므로 민감한 정보를 클라이언트에 노출시키지 않고 데이터베이스에 직접 액세스할 수 있습니다.

향상된 동시 렌더링

  1. 향상된 서스펜스

React 19는 더 나은 폴백 처리를 통해 Suspense 구성 요소를 강화하고 있습니다.

React 18 예시:

function ProfilePage({ userId }) {
  return (
    <Suspense fallback={<h1>Loading profile...</h1>}>
      <ProfileDetails userId={userId} />
      <Suspense fallback={<h2>Loading posts...</h2>}>
        <ProfileTimeline userId={userId} />
      </Suspense>
    </Suspense>
  );
}

React 19의 잠재적인 개선(추측):

function ProfilePage({ userId }) {
  return (
    <Suspense
      fallback={<h1>Loading profile...</h1>}
      primaryContent={<ProfileDetails userId={userId} />}
    >
      <ProfileTimeline userId={userId} />
    </Suspense>
  );
}

이 추측적인 React 19 예에서, mainContent prop을 사용하면 개발자가 로드 중에 우선순위를 지정해야 하는 콘텐츠를 지정할 수 있습니다.

  1. 확장된 자동 렌더링 배치

React 18에서는 setState 및 후크에 대한 자동 일괄 처리를 도입했습니다. React 19에서는 이를 더 많은 시나리오로 확장할 수 있습니다.

React 18 예시:

function Counter() {
  const [count, setCount] = useState(0);

  function handleClick() {
    setCount(c => c + 1); // Does not re-render yet
    setCount(c => c + 1); // Does not re-render yet
    // React will only re-render once at the end (that's batching!)
  }

  return <button onClick={handleClick}>{count}</button>;
}

React 19는 이 일괄 처리를 잠재적으로 비동기 작업을 포함하여 더 많은 시나리오로 확장할 수 있습니다.

  1. 세밀하게 조정된 우선순위 기반 렌더링

React 19에서는 렌더링 우선순위에 대한 보다 세부적인 제어 기능을 도입할 수 있습니다.

잠재적 React 19 예(추측):

import { useDeferredValue, startTransition } from 'react';

function SearchResults({ query }) {
  const deferredQuery = useDeferredValue(query);

  return (
    <>
      <div>Searching for: {query}</div>
      <Suspense fallback={<Spinner />}>
        <Results query={deferredQuery} />
      </Suspense>
    </>
  );
}

function handleSearch(input) {
  startTransition(() => {
    setSearchQuery(input);
  });
}

이 예에서 React 19는 사용자 입력에 응답하여 UI의 다양한 부분이 업데이트되는 방식을 보다 세밀하게 제어할 수 있습니다.

새로운 후크 및 API

  1. 이벤트 후크 사용

React 19에서는 오래된 클로저 문제를 해결하기 위해 useEvent 후크를 도입할 예정입니다.

React 18 문제:

function ChatRoom({ roomId }) {
  const [message, setMessage] = useState('');

  function handleSend() {
    // This might use a stale `roomId` if the component re-renders
    sendMessage(roomId, message);
  }

  return <button onClick={handleSend}>Send</button>;
}

useEvent를 사용한 잠재적인 React 19 솔루션:

function ChatRoom({ roomId }) {
  const [message, setMessage] = useState('');

  const handleSend = useEvent(() => {
    // This will always use the current `roomId`
    sendMessage(roomId, message);
  });

  return <button onClick={handleSend}>Send</button>;
}
  1. 향상된 컨텍스트 API

React 19에는 성능 문제를 해결하기 위해 Context API 개선 사항이 포함될 수 있습니다.

React 18 예시:

const ThemeContext = React.createContext('light');

function App() {
  const [theme, setTheme] = useState('light');
  return (
    <ThemeContext.Provider value={theme}>
      <Header />
      <Main />
      <Footer />
    </ThemeContext.Provider>
  );
}

React 19의 잠재적인 개선(추측):

const ThemeContext = React.createContext('light', (prev, next) => prev === next);

function App() {
  const [theme, setTheme] = useState('light');
  return (
    <ThemeContext.Provider value={theme}>
      <Header />
      <Main />
      <Footer />
    </ThemeContext.Provider>
  );
}

이 추측적인 예에서는 컨텍스트에 불필요한 재렌더링을 방지하기 위한 비교 기능이 포함될 수 있습니다.

성능 최적화

많은 성능 최적화가 내부적으로 이루어지지만 일부는 개발자에게 표시될 수도 있습니다.

  1. 향상된 비교 알고리즘

React 19는 조정 프로세스를 최적화할 것으로 예상됩니다. 코드를 변경할 필요는 없지만 복잡한 UI를 더 빠르게 업데이트할 수 있습니다.

  1. Memory Usage Improvements

React 19 may include optimizations to reduce memory usage. Again, this might not require code changes but could improve performance, especially for large applications.

  1. Better Tree Shaking

React 19 might improve tree shaking capabilities. This could result in smaller bundle sizes when using build tools like Vite.

Example vite.config.js that might better leverage React 19's tree shaking:

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

export default defineConfig({
  plugins: [react()],
  build: {
    rollupOptions: {
      output: {
        manualChunks(id) {
          if (id.includes('node_modules')) {
            return 'vendor';
          }
        }
      }
    }
  }
})

Migration Tips

  1. Stay Informed: Keep an eye on the official React blog and documentation for updates.
  2. Experiment in Non-Production Environments: Try the React 19 RC in development or staging environments.
  3. Review Deprecated APIs: Check the documentation for any deprecated APIs and plan updates accordingly.
  4. Leverage New Features Gradually: Implement new features in non-critical parts of your application first.
  5. Optimize Rendering: Review your component structure and use of Suspense boundaries.
  6. Comprehensive Testing: Thoroughly test your application, especially areas relying on React's internal APIs.

Using React 19 RC with Vite

To experiment with the React 19 Release Candidate using Vite:

  1. Create a new Vite project:
   npm create vite@latest my-react-19-rc-app -- --template react
  1. Navigate to the project directory:
   cd my-react-19-rc-app
  1. Install the React 19 RC versions:
   npm install react@rc react-dom@rc
  1. Update your vite.config.js:
   import { defineConfig } from 'vite'
   import react from '@vitejs/plugin-react'

   export default defineConfig({
     plugins: [react()],
     esbuild: {
       jsxInject: `import React from 'react'`
     },
     optimizeDeps: {
       include: ['react', 'react-dom']
     }
   })
  1. Start the development server:
   npm run dev

Remember, using the RC version in production is not recommended.

Conclusion

While React 19 is still in the Release Candidate stage, it promises exciting improvements and new features. From enhanced server-side rendering to new hooks and performance optimizations, there's much to explore in React 19.

As the release date approaches, stay tuned to the official React documentation and community resources for the most up-to-date information. By staying informed and gradually adopting new features as they become stable, you'll be well-positioned to leverage the improvements in React 19 for your projects.

위 내용은 React와 React(RC): 주요 차이점 및 예제가 포함된 마이그레이션 팁의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.