๐Ÿ“ฆ noxify / vite-rsc-ssg-renoun

๐Ÿ“„ development-react18-performance.mdx ยท 156 lines
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156---
title: Building Performant Web Applications with React 18
date: 2024-10-08
summary: Discover React 18's new features including concurrent rendering, automatic batching, and Suspense to build faster web applications.
category: Development
tags:
  - react18
  - performance
  - concurrent
  - suspense
---

React 18 introduced groundbreaking features that fundamentally change how we build performant web applications. In this post, we'll explore these new capabilities and learn how to leverage them for better user experiences.

## Concurrent Rendering and startTransition

React 18's concurrent features allow you to mark updates as non-urgent, preventing them from blocking user interactions:

```tsx path="components/SearchResults.tsx"
import { useState, useTransition, useDeferredValue } from 'react'

export function SearchResults() {
  const [query, setQuery] = useState('')
  const [isPending, startTransition] = useTransition()
  const deferredQuery = useDeferredValue(query)
  
  const handleSearch = (value: string) => {
    setQuery(value)
    // Mark expensive search as non-urgent
    startTransition(() => {
      // This update won't block urgent updates
      performExpensiveSearch(value)
    })
  }

  return (
    <div>
      <input 
        value={query}
        onChange={(e) => handleSearch(e.target.value)}
        placeholder="Search..."
      />
      {isPending && <div>Searching...</div>}
      <Results query={deferredQuery} />
    </div>
  )
}
```

## Automatic Batching

React 18 automatically batches multiple state updates, even in promises and event handlers:

```tsx path="components/UserDashboard.tsx"
import { useState } from 'react'

export function UserDashboard() {
  const [count, setCount] = useState(0)
  const [loading, setLoading] = useState(false)

  const handleAsyncUpdate = async () => {
    // These updates are automatically batched in React 18
    setLoading(true)
    setCount(prev => prev + 1)
    
    try {
      await fetch('/api/update')
      // These are also batched together
      setLoading(false)
      setCount(prev => prev + 1)
    } catch (error) {
      setLoading(false)
    }
  }

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={handleAsyncUpdate} disabled={loading}>
        {loading ? 'Updating...' : 'Update'}
      </button>
    </div>
  )
}
```

## Enhanced Suspense with Error Boundaries

Combine Suspense with error boundaries for robust loading states:

```tsx path="components/DataWrapper.tsx"
import { Suspense } from 'react'
import { ErrorBoundary } from './ErrorBoundary'

function LoadingFallback() {
  return (
    <div className="loading-spinner">
      <div>Loading...</div>
    </div>
  )
}

function ErrorFallback({ error }: { error: Error }) {
  return (
    <div className="error-message">
      <h2>Something went wrong</h2>
      <p>{error.message}</p>
      <button onClick={() => window.location.reload()}>
        Try again
      </button>
    </div>
  )
}

export function DataWrapper({ children }: { children: React.ReactNode }) {
  return (
    <ErrorBoundary fallback={ErrorFallback}>
      <Suspense fallback={<LoadingFallback />}>
        {children}
      </Suspense>
    </ErrorBoundary>
  )
}
```

## useSyncExternalStore for External State

Safely subscribe to external stores with the new useSyncExternalStore hook:

```tsx path="hooks/useWindowSize.tsx"
import { useSyncExternalStore } from 'react'

function subscribe(callback: () => void) {
  window.addEventListener('resize', callback)
  return () => window.removeEventListener('resize', callback)
}

function getSnapshot() {
  return {
    width: window.innerWidth,
    height: window.innerHeight
  }
}

export function useWindowSize() {
  return useSyncExternalStore(
    subscribe,
    getSnapshot,
    () => ({ width: 0, height: 0 }) // Server snapshot
  )
}
```

## Conclusion

React 18's new features provide powerful tools for building more responsive and performant applications. By adopting concurrent rendering, automatic batching, and enhanced Suspense, you can create better user experiences with smoother interactions and more predictable loading states.