### Full Example: Conditional Rendering with Context
Source: https://ko.react.dev/reference/react/use
This example demonstrates how to use the `use` hook within conditional logic to conditionally render UI elements based on context values. It includes context definition, provider setup, and conditional usage in components.
```javascript
import { createContext, use } from 'react';
const ThemeContext = createContext(null);
export default function MyApp() {
return (
)
}
function Form() {
return (
);
}
function Panel({ title, children }) {
const theme = use(ThemeContext);
const className = 'panel-' + theme;
return (
{title}
{children}
)
}
function Button({ show, children }) {
if (show) {
const theme = use(ThemeContext);
const className = 'button-' + theme;
return (
);
}
return false
}
```
```css
.panel-light,
.panel-dark {
border: 1px solid black;
border-radius: 4px;
padding: 20px;
}
.panel-light {
color: #222;
background: #fff;
}
.panel-dark {
color: #fff;
background: rgb(23, 32, 42);
}
.button-light,
.button-dark {
border: 1px solid #777;
padding: 5px;
margin-right: 10px;
margin-top: 10px;
}
.button-dark {
background: #222;
color: #fff;
}
.button-light {
background: #fff;
color: #222;
}
```
--------------------------------
### Markdown Editor Example
Source: https://ko.react.dev/reference/react-dom/components/textarea
This example demonstrates a controlled textarea for markdown input and a preview pane that updates in real-time. It requires the 'remarkable' library for markdown rendering.
```javascript
import { useState } from 'react';
import MarkdownPreview from './MarkdownPreview.js';
export default function MarkdownEditor() {
const [postContent, setPostContent] = useState('_Hello,_ **Markdown**!');
return (
<>
>
);
}
```
```javascript
import { Remarkable } from 'remarkable';
const md = new Remarkable();
export default function MarkdownPreview({ markdown }) {
const renderedHTML = md.render(markdown);
return ;
}
```
```json
{
"dependencies": {
"react": "latest",
"react-dom": "latest",
"react-scripts": "latest",
"remarkable": "2.0.1"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
}
}
```
```css
textarea { display: block; margin-top: 5px; margin-bottom: 10px; }
```
--------------------------------
### Basic resumeAndPrerender Usage
Source: https://ko.react.dev/reference/react-dom/static/resumeAndPrerender
This example shows how to use resumeAndPrerender to continue a prerendered React tree and return the prelude as an HTML response.
```javascript
import { resumeAndPrerender } from 'react-dom/static';
import { getPostponedState } from 'storage';
async function handler(request, response) {
const postponedState = getPostponedState(request);
const { prelude } = await resumeAndPrerender(, postponedState, {
bootstrapScripts: ['/main.js']
});
return new Response(prelude, {
headers: { 'content-type': 'text/html' },
});
}
```
--------------------------------
### Example: Using useContext with a fallback default value
Source: https://ko.react.dev/reference/react/useContext
This example demonstrates how a component using `useContext` behaves when rendered outside of its Provider. The `Button` and `Panel` components correctly use the default 'light' theme because `ThemeContext` is not wrapped around them in the initial render.
```javascript
import { createContext, useContext, useState } from 'react';
const ThemeContext = createContext('light');
export default function MyApp() {
const [theme, setTheme] = useState('light');
return (
<>
>
)
}
function Form({ children }) {
return (
);
}
function Panel({ title, children }) {
const theme = useContext(ThemeContext);
const className = 'panel-' + theme;
return (
{title}
{children}
)
}
function Button({ children, onClick }) {
const theme = useContext(ThemeContext);
const className = 'button-' + theme;
return (
);
}
```
```css
.panel-light,
.panel-dark {
border: 1px solid black;
border-radius: 4px;
padding: 20px;
margin-bottom: 10px;
}
.panel-light {
color: #222;
background: #fff;
}
.panel-dark {
color: #fff;
background: rgb(23, 32, 42);
}
.button-light,
.button-dark {
border: 1px solid #777;
padding: 5px;
margin-right: 10px;
margin-top: 10px;
}
.button-dark {
background: #222;
color: #fff;
}
.button-light {
background: #fff;
color: #222;
}
```
--------------------------------
### Example Usage of defaultProps
Source: https://ko.react.dev/reference/react/Component
Demonstrates how defaultProps are applied when a prop is missing, undefined, or explicitly set to null.
```javascript
<>
{/* this.props.color is "blue" */}
{/* this.props.color is "blue" */}
{/* this.props.color is null */}
{/* this.props.color is "red" */}
>
```
--------------------------------
### Resume prerendered React tree to Node.js Stream
Source: https://ko.react.dev/reference/react-dom/static/resumeAndPrerenderToNodeStream
Use resumeAndPrerenderToNodeStream to continue a prerendered React tree to a static HTML string. This example shows how to get postponed state, resume rendering, and pipe the prelude stream to a writable response.
```javascript
import { resumeAndPrerenderToNodeStream } from 'react-dom/static';
import { getPostponedState } from 'storage';
async function handler(request, writable) {
const postponedState = getPostponedState(request);
const { prelude } = await resumeAndPrerenderToNodeStream(, JSON.parse(postponedState));
prelude.pipe(writable);
}
```
--------------------------------
### useCallback Usage
Source: https://ko.react.dev/reference/react/useCallback
This example demonstrates how to use the useCallback hook to memoize a function that makes an API call. The function `handleSubmit` will only be recreated if `productId` or `referrer` changes.
```APIDOC
## useCallback(fn, dependencies)
### Description
Memoizes a function to preserve its reference across renders, preventing unnecessary re-creations unless dependencies change.
### Parameters
* `fn` (function): The function to memoize. It can accept any arguments and return any value. React returns this function as-is on the first render. On subsequent renders, if the `dependencies` have not changed, React returns the previously memoized function. Otherwise, it returns the new function passed in this render and caches it for future use.
* `dependencies` (array): A list of all reactive values (props, state, variables, functions declared within the component) that `fn` references. The linter will verify that all reactive values are correctly listed. The dependency array must have a stable number of elements and be written inline, e.g., `[dep1, dep2, dep3]`.
### Returns
* (function): The memoized function. On initial render, it returns the `fn` you passed. On subsequent renders, it returns either the previously cached function (if dependencies haven't changed) or the `fn` from the current render.
### Caveats
* `useCallback` can only be called at the top level of your component or custom Hook, not inside loops, conditions, or nested functions.
* React generally does not clear cached functions unless there's a specific reason, such as during development when editing files or when a component suspends during initial mount. Relying on `useCallback` for performance optimization should align with these behaviors.
```
--------------------------------
### Flushing Updates for Third-Party Integrations
Source: https://ko.react.dev/reference/react-dom/flushSync
Example demonstrating how to use flushSync when integrating with third-party code like browser APIs or UI libraries that expect immediate DOM updates.
```APIDOC
## Flushing Updates for Third-Party Integrations
### Description
When integrating with third-party code, such as browser APIs or UI libraries, you might need to force React to process updates. `flushSync` ensures that all state updates within the callback are processed synchronously, updating the DOM immediately. This guarantees that subsequent code runs after the DOM has been updated.
### Usage Example
```javascript
import { flushSync } from 'react-dom';
flushSync(() => {
// State update that needs to be flushed immediately
setSomething(123);
});
// By this line, the DOM is updated.
```
### Pitfall
`flushSync` is not commonly used and can significantly degrade application performance if used frequently. It should be used as a last resort, primarily when integrating with external systems that require immediate DOM synchronization.
### Use Case: `onbeforeprint` API
This example shows how `flushSync` can be used with the `onbeforeprint` browser API to update the DOM before the print dialog opens.
```javascript
import { useState, useEffect } from 'react';
import { flushSync } from 'react-dom';
export default function PrintApp() {
const [isPrinting, setIsPrinting] = useState(false);
useEffect(() => {
function handleBeforePrint() {
flushSync(() => {
setIsPrinting(true);
});
}
function handleAfterPrint() {
setIsPrinting(false);
}
window.addEventListener('beforeprint', handleBeforePrint);
window.addEventListener('afterprint', handleAfterPrint);
return () => {
window.removeEventListener('beforeprint', handleBeforePrint);
window.removeEventListener('afterprint', handleAfterPrint);
};
}, []);
return (
<>
isPrinting: {isPrinting ? 'yes' : 'no'}
>
);
}
```
Without `flushSync`, the print dialog might appear before the `isPrinting` state is updated, showing 'no' instead of 'yes'.
```
--------------------------------
### observeUsing
Source: https://ko.react.dev/reference/react/Fragment
Starts observing all direct DOM children of the Fragment using the provided IntersectionObserver or ResizeObserver instance.
```APIDOC
## observeUsing(observer)
### Description
Starts observing all first-level DOM children of the Fragment with the provided observer.
### Method
`observeUsing`
### Parameters
#### Path Parameters
- **observer** (IntersectionObserver | ResizeObserver) - Required - An [`IntersectionObserver`](https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver) or [`ResizeObserver`](https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserver) instance.
### Returns
`observeUsing` does not return anything (`undefined`).
```
--------------------------------
### Basic Optimistic State Update Example
Source: https://ko.react.dev/reference/react/useOptimistic
Illustrates a simple optimistic update where a temporary state 'b' is shown while saving changes. The actual state is updated only after the asynchronous operation completes.
```javascript
const [value, setValue] = useState('a');
const [optimistic, setOptimistic] = useOptimistic(value);
startTransition(async () => {
setOptimistic('b');
const newValue = await saveChanges('b');
setValue(newValue);
});
```
--------------------------------
### Stopwatch with State and Refs
Source: https://ko.react.dev/reference/react/useRef
This stopwatch example combines state for values used in rendering (`startTime`, `now`) and a ref for a value not used in rendering (interval ID). The interval ID is stored in a ref so it can be cleared later.
```javascript
import { useState, useRef } from 'react';
export default function Stopwatch() {
const [startTime, setStartTime] = useState(null);
const [now, setNow] = useState(null);
const intervalRef = useRef(null);
function handleStart() {
setStartTime(Date.now());
setNow(Date.now());
clearInterval(intervalRef.current);
intervalRef.current = setInterval(() => {
setNow(Date.now());
}, 10);
}
function handleStop() {
clearInterval(intervalRef.current);
}
let secondsPassed = 0;
if (startTime != null && now != null) {
secondsPassed = (now - startTime) / 1000;
}
return (
<>
Time passed: {secondsPassed.toFixed(3)}
>
);
}
```
--------------------------------
### Counter component with updater function
Source: https://ko.react.dev/reference/react/useState
This example demonstrates a Counter component where clicking the '+3' button correctly increments the age by three using an updater function passed to `setAge`.
```javascript
import { useState } from 'react';
export default function Counter() {
const [age, setAge] = useState(42);
function increment() {
setAge(a => a + 1);
}
return (
<>
Your age: {age}
>
);
}
```
--------------------------------
### Track Clicks with useRef
Source: https://ko.react.dev/reference/react/useRef
This example uses a ref to track the number of button clicks. Since the click count is only read and written within event handlers, a ref is suitable here instead of state.
```javascript
import { useRef } from 'react';
export default function Counter() {
let ref = useRef(0);
function handleClick() {
ref.current = ref.current + 1;
alert('You clicked ' + ref.current + ' times!');
}
return (
);
}
```
--------------------------------
### Observe Fragment's first-level DOM children
Source: https://ko.react.dev/reference/react/Fragment
Use `observeUsing` to start observing direct DOM children of the Fragment with a provided `IntersectionObserver` or `ResizeObserver`.
```javascript
const observer = new IntersectionObserver(callback, options);
fragmentRef.current.observeUsing(observer);
```
--------------------------------
### Use flushSync with the onbeforeprint API
Source: https://ko.react.dev/reference/react-dom/flushSync
This example demonstrates using `flushSync` within the `onbeforeprint` browser API to immediately "flush" React state to the DOM before the print dialog opens. This ensures that any changes made to the state are reflected in the printed output.
```javascript
import { useState, useEffect } from 'react';
import { flushSync } from 'react-dom';
export default function PrintApp() {
const [isPrinting, setIsPrinting] = useState(false);
useEffect(() => {
function handleBeforePrint() {
flushSync(() => {
setIsPrinting(true);
})
}
function handleAfterPrint() {
setIsPrinting(false);
}
window.addEventListener('beforeprint', handleBeforePrint);
window.addEventListener('afterprint', handleAfterPrint);
return () => {
window.removeEventListener('beforeprint', handleBeforePrint);
window.removeEventListener('afterprint', handleAfterPrint);
}
}, []);
return (
<>
isPrinting: {isPrinting ? 'yes' : 'no'}
>
);
}
```
--------------------------------
### Caching Function Results vs. Functions with useCallback and useMemo
Source: https://ko.react.dev/reference/react/useCallback
This example demonstrates how useMemo caches the result of a function call, while useCallback caches the function itself. Both are used to optimize child components by preventing unnecessary re-renders when props do not change.
```javascript
import { useMemo, useCallback } from 'react';
function ProductPage({ productId, referrer }) {
const product = useData('/product/' + productId);
const requirements = useMemo(() => {
return computeRequirements(product);
}, [product]);
const handleSubmit = useCallback((orderDetails) => {
post('/product/' + productId + '/buy', {
referrer,
orderDetails,
});
}, [productId, referrer]);
return (
);
}
```
--------------------------------
### Remove a React App from a DOM Element
Source: https://ko.react.dev/reference/react-dom/unmountComponentAtNode
This example demonstrates how to conditionally render and unmount a React application from a DOM element. It's useful for integrating React into existing non-React pages or for managing specific React-powered sections.
```javascript
import './styles.css';
import { render, unmountComponentAtNode } from 'react-dom';
import App from './App.js';
const domNode = document.getElementById('root');
document.getElementById('render').addEventListener('click', () => {
render(, domNode);
});
document.getElementById('unmount').addEventListener('click', () => {
unmountComponentAtNode(domNode);
});
```
--------------------------------
### Pure Reducer Function Example
Source: https://ko.react.dev/reference/react/useReducer
This reducer correctly replaces the state instead of mutating it, making it a pure function. This is the recommended approach for updating state in React.
```javascript
function reducer(state, action) {
switch (action.type) {
case 'added_todo': {
// ✅ Correct: replacing with new state
return {
...state,
todos: [
...state.todos,
{ id: nextId++, text: action.text }
]
};
}
// ...
}
}
```
--------------------------------
### Counter component without updater function
Source: https://ko.react.dev/reference/react/useState
This example shows a Counter component where the '+3' button does not work as expected because `setAge` is called with the current `age` value directly, leading to stale state.
```javascript
import { useState } from 'react';
export default function Counter() {
const [age, setAge] = useState(42);
function increment() {
setAge(age + 1);
}
return (
<>
Your age: {age}
>
);
}
```
--------------------------------
### Add Separators Between Children using Children.forEach
Source: https://ko.react.dev/reference/react/Children
Use `Children.forEach` to iterate over children and insert a separator (``) between each one. This example builds a new array by pushing children and separators, then removes the trailing separator.
```javascript
import { Children } from 'react';
export default function SeparatorList({ children }) {
const result = [];
Children.forEach(children, (child, index) => {
result.push(child);
result.push();
});
result.pop(); // Remove the last separator
return result;
}
```
```javascript
import SeparatorList from './SeparatorList.js';
export default function App() {
return (
This is the first item.
This is the second item.
This is the third item.
);
}
```
--------------------------------
### Pass Root Options to createRoot, Not root.render
Source: https://ko.react.dev/reference/react-dom/client/createRoot
Root options should be passed to `createRoot(...)`, not `root.render(...)`. The `root.render` method only accepts one argument.
```javascript
// 🚩 Incorrect way: root.render only accepts one argument.
root.render(App, {onUncaughtError});
// ✅ Correct way: Options are passed to createRoot.
const root = createRoot(container, {onUncaughtError});
root.render();
```
--------------------------------
### Render a React App with createRoot
Source: https://ko.react.dev/reference/react-dom/client/createRoot
Ensure you are actually rendering your app to the root. Without the `root.render(...)` call, nothing will be displayed.
```javascript
import { createRoot } from 'react-dom/client';
import App from './App.js';
const root = createRoot(document.getElementById('root'));
root.render();
```
--------------------------------
### Setting up React App with StrictMode
Source: https://ko.react.dev/reference/react/StrictMode
This code demonstrates how to wrap your React application with StrictMode in the root render function. This enables additional development-time checks and warnings.
```javascript
import { createRoot } from 'react-dom/client';
import {StrictMode} from 'react';
import './styles.css';
import App from './App';
const root = createRoot(document.getElementById("root"));
// ✅ Using StrictMode.
root.render(
);
```
--------------------------------
### Impure Reducer Function Example
Source: https://ko.react.dev/reference/react/useReducer
This reducer mutates the state array, which is an impure operation. React's Strict Mode will call this twice in development, revealing the mutation.
```javascript
function reducer(state, action) {
switch (action.type) {
case 'added_todo': {
// 🚩 Mistake: mutating state
state.todos.push({ id: nextId++, text: action.text });
return state;
}
// ...
}
}
```
--------------------------------
### Create Context with 'light' fallback
Source: https://ko.react.dev/reference/react/useContext
Initialize a Context with a meaningful default value like 'light'. This ensures components don't break if rendered without a Provider.
```javascript
const ThemeContext = createContext('light');
```
--------------------------------
### Get bounding rectangles of Fragment's children
Source: https://ko.react.dev/reference/react/Fragment
The `getClientRects()` method returns an array of `DOMRect` objects, each representing the bounding box of a first-level DOM child within the Fragment.
```javascript
const rects = fragmentRef.current.getClientRects();
```
--------------------------------
### Get the root node containing the Fragment
Source: https://ko.react.dev/reference/react/Fragment
Use `getRootNode()` to retrieve the root node of the Fragment's parent DOM node, similar to `Node.getRootNode()`. Options can be passed to control behavior.
```javascript
const root = fragmentRef.current.getRootNode();
```
--------------------------------
### Simplified useCallback Implementation
Source: https://ko.react.dev/reference/react/useCallback
This simplified implementation shows how useCallback can be thought of as a specialized useMemo hook that returns the function itself.
```javascript
// (React 내부의) 단순화된 구현 형태
function useCallback(fn, dependencies) {
return useMemo(() => fn, dependencies);
}
```
--------------------------------
### Buggy Ref Callback Without Cleanup
Source: https://ko.react.dev/reference/react/StrictMode
This ref callback adds an item to a list but lacks cleanup logic, causing a memory leak. StrictMode highlights this issue by re-running setup and cleanup.
```jsx
{
const list = itemsRef.current;
const item = {animal, node};
list.push(item);
return () => {
// 🚩 No cleanup, this is a bug!
}
}}
>
```
--------------------------------
### resumeAndPrerender(reactNode, postponedState, options?)
Source: https://ko.react.dev/reference/react-dom/static/resumeAndPrerender
Call resumeAndPrerender to continue a prerendered React tree to a static HTML string. This function is part of the static server-side generation (SSG) capabilities of React DOM.
```APIDOC
## resumeAndPrerender(reactNode, postponedState, options?)
### Description
Call `resumeAndPrerender` to continue a prerendered React tree to a static HTML string. This API is used for static server-side generation (SSG) and can resume a previously aborted prerendering process.
### Method
```javascript
resumeAndPrerender(reactNode, postponedState, options?)
```
### Parameters
* `reactNode`: The React node that was initially used with `prerender` or a previous `resumeAndPrerender` call. It should represent the entire document, including the `` tag.
* `postponedState`: An opaque `postpone` object obtained from a previous prerendering operation, typically stored and retrieved from a persistent store.
* `options` (Optional): An object that configures streaming behavior.
* `signal` (Optional): An AbortSignal to allow aborting the server rendering process, enabling client-side rendering for the remainder.
* `onError` (Optional): A callback function that is invoked when a server error occurs. By default, it logs the error to the console. Custom implementations should consider logging crash reports and potentially calling `console.error`.
### Returns
Returns a Promise that resolves to an object with the following properties upon successful rendering:
* `prelude`: A Web Stream that outputs the generated HTML. This stream can be consumed chunk by chunk or read entirely as a string.
* `postponed`: A JSON-serializable, opaque object that can be passed to `resume` or `resumeAndPrerender` if the rendering process is aborted.
If rendering fails, the Promise will be rejected, allowing for fallback shell rendering.
### Caveats
* The `nonce` option is not available for `resumeAndPrerender` due to security implications with Content Security Policy (CSP).
### Example
```javascript
import { resumeAndPrerender } from 'react-dom/static';
import { getPostponedState } from 'storage';
async function handler(request, response) {
const postponedState = getPostponedState(request);
const { prelude } = await resumeAndPrerender(, postponedState, {
bootstrapScripts: ['/main.js']
});
return new Response(prelude, {
headers: { 'content-type': 'text/html' },
});
}
```
```
--------------------------------
### Updating Optimistic State with useOptimistic
Source: https://ko.react.dev/reference/react/useOptimistic
Demonstrates how to use the setter function returned by useOptimistic to update state optimistically within a transition. This is useful for immediate UI feedback before an asynchronous operation completes.
```javascript
const [optimisticLike, setOptimisticLike] = useOptimistic(false);
const [optimisticSubs, setOptimisticSubs] = useOptimistic(subs);
function handleClick() {
startTransition(async () => {
setOptimisticLike(true);
setOptimisticSubs(a => a + 1);
await saveChanges();
});
}
```
--------------------------------
### flushSync(callback)
Source: https://ko.react.dev/reference/react-dom/flushSync
Forces React to process all pending operations and update the DOM synchronously. Use this as a last resort.
```APIDOC
## flushSync(callback)
### Description
Calls `flushSync` to force React to process all pending operations and update the DOM synchronously. This ensures that the DOM is updated immediately after the callback.
### Method
`flushSync`
### Parameters
#### Function Parameter
* `callback` (function) - Required - A function that contains the state updates you want to process synchronously. React will immediately invoke this callback and process all updates within it.
### Request Example
```javascript
import { flushSync } from 'react-dom';
flushSync(() => {
setSomething(123);
});
```
### Returns
`flushSync` returns `undefined`.
### Caveats
* Using `flushSync` can significantly degrade your application's performance and should be avoided in most cases.
* It can force pending Suspense boundaries to show their fallback state.
* It can execute pending effects and synchronously apply any updates within them before returning.
* It may process updates outside the callback if necessary, such as pending updates from a click event, before processing updates inside the callback.
```
--------------------------------
### resumeAndPrerenderToNodeStream
Source: https://ko.react.dev/reference/react-dom/static/resumeAndPrerenderToNodeStream
Call `resumeAndPrerenderToNodeStream` to continue a prerendered React tree to a static HTML string. This function is specific to Node.js environments.
```APIDOC
## resumeAndPrerenderToNodeStream(reactNode, postponedState, options?)
### Description
Call `resumeAndPrerenderToNodeStream` to continue a prerendered React tree to a static HTML string.
### Parameters
* `reactNode`: The React node you called `prerender` (or a previous `resumeAndPrerenderToNodeStream`) with. For example, a JSX element like ``. It is expected to represent the entire document, so the `App` component should render the `` tag.
* `postponedState`: The opaque `postpone` object returned from a [prerender API](/reference/react-dom/static/index), loaded from wherever you stored it (e.g. redis, a file, or S3).
* `options` (optional): An object with streaming options.
* `signal` (optional): An [abort signal](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal) that lets you [abort server rendering](#aborting-server-rendering) and render the rest on the client.
* `onError` (optional): A callback that fires whenever there is a server error, whether [recoverable](#recovering-from-errors-outside-the-shell) or [not.](#recovering-from-errors-inside-the-shell) By default, this only calls `console.error`. If you override it to [log crash reports,](#logging-crashes-on-the-server) make sure that you still call `console.error`.
### Returns
`resumeAndPrerenderToNodeStream` returns a Promise:
- If rendering the is successful, the Promise will resolve to an object containing:
- `prelude`: a [Web Stream](https://developer.mozilla.org/en-US/docs/Web/API/Streams_API) of HTML. You can use this stream to send a response in chunks, or you can read the entire stream into a string.
- `postponed`: an JSON-serializeable, opaque object that can be passed to [`resumeToNodeStream`](/reference/react-dom/server/resume) or [`resumeAndPrerenderToNodeStream`](/reference/react-dom/static/resumeAndPrerenderToNodeStream) if `resumeAndPrerenderToNodeStream` is aborted.
- If rendering fails, the Promise will be rejected. [Use this to output a fallback shell.](/reference/react-dom/server/renderToReadableStream#recovering-from-errors-inside-the-shell)
### Caveats
`nonce` is not an available option when prerendering. Nonces must be unique per request and if you use nonces to secure your application with [CSP](https://developer.org/en-US/docs/Web/HTTP/Guides/CSP) it would be inappropriate and insecure to include the nonce value in the prerender itself.
### Example
```js
import { resumeAndPrerenderToNodeStream } from 'react-dom/static';
import { getPostponedState } from 'storage';
async function handler(request, writable) {
const postponedState = getPostponedState(request);
const { prelude } = await resumeAndPrerenderToNodeStream(, JSON.parse(postponedState));
prelude.pipe(writable);
}
```
```
--------------------------------
### static contextType
Source: https://ko.react.dev/reference/react/Component
Allows a class component to read context. The context specified must be created with `createContext`.
```APIDOC
## static contextType
### Description
Specifies the context that a class component needs to read. The context value must be created using `createContext`.
### Usage
```javascript
class Button extends Component {
static contextType = ThemeContext;
render() {
const theme = this.context;
const className = 'button-' + theme;
return (
);
}
}
```
### Note
Reading `this.context` in class components is equivalent to using `useContext` in function components.
```
--------------------------------
### Use hydrateRoot for Server-Rendered Apps
Source: https://ko.react.dev/reference/react-dom/client/createRoot
If your app is server-rendered and includes React's initial HTML, use `hydrateRoot` instead of `createRoot`. This prevents the HTML from being discarded and re-created from scratch, preserving user experience.
```javascript
import { hydrateRoot } from 'react-dom/client';
import App from './App.js';
hydrateRoot(
document.getElementById('root'),
);
```
--------------------------------
### Create Context with null fallback
Source: https://ko.react.dev/reference/react/useContext
Initialize a Context with `null` as its default value. This is the default behavior if no value is explicitly provided during creation.
```javascript
const ThemeContext = createContext(null);
```
--------------------------------
### Project Dependencies: React Canary
Source: https://ko.react.dev/reference/react/Fragment
Specifies the project dependencies, including 'react' and 'react-dom' using the 'canary' version, and 'react-scripts' for build tooling.
```json
{
"dependencies": {
"react": "canary",
"react-dom": "canary",
"react-scripts": "latest"
}
}
```
--------------------------------
### Mock API Actions for Cart Operations
Source: https://ko.react.dev/reference/react/useOptimistic
Simulates asynchronous API calls for adding, removing, and updating quantities in the shopping cart. These functions include a delay to mimic network latency.
```javascript
export async function addToCart(item) {
await new Promise((res) => setTimeout(res, 800));
}
export async function removeFromCart(id) {
await new Promise((res) => setTimeout(res, 800));
}
export async function updateQuantity(id, quantity) {
await new Promise((res) => setTimeout(res, 800));
}
```
--------------------------------
### Render a Component with root.render
Source: https://ko.react.dev/reference/react-dom/client/createRoot
Ensure you are passing a React component to `root.render`. Passing a function directly or the result of a function call without JSX can lead to errors.
```javascript
// 🚩 Incorrect way: App is a function, not a component.
root.render(App);
// ✅ Correct way: is a component.
root.render();
```
```javascript
// 🚩 Incorrect way: createApp is a function, not a component.
root.render(createApp);
// ✅ Correct way: Call createApp to return a component.
root.render(createApp());
```
--------------------------------
### Simplifying Dependencies by Moving to Inner Scope
Source: https://ko.react.dev/reference/react/useMemo
For calculations within useMemo, define any intermediate objects or values directly inside the memoization function. This simplifies the dependency array of the outer useMemo, as it now directly depends on primitive values rather than potentially unstable object references.
```javascript
function Dropdown({ allItems, text }) {
const visibleItems = useMemo(() => {
const searchOptions = { matchMode: 'whole-word', text };
return searchItems(allItems, searchOptions);
}, [allItems, text]); // ✅ allItems이나 text가 변경될 때만 변경
// ...
```
--------------------------------
### Force synchronous updates with flushSync
Source: https://ko.react.dev/reference/react-dom/flushSync
Use `flushSync` to force React to process all updates within the callback synchronously. This ensures the DOM is updated immediately. Use this as a last resort, as it can degrade performance.
```javascript
import { flushSync } from 'react-dom';
flushSync(() => {
setSomething(123);
});
```
--------------------------------
### Provide Context value
Source: https://ko.react.dev/reference/react/use
Wrap a component or its ancestors with a Context Provider to make its value available. The `value` prop sets the context value.
```javascript
function MyPage() {
return (
);
}
function Form() {
// ... render buttons ...
}
```
--------------------------------
### Use flushSync in Event Handlers
Source: https://ko.react.dev/reference/react-dom/flushSync
Calling `flushSync` within an event handler is the recommended and safe way to ensure synchronous updates.
```javascript
function handleClick() {
// ✅ Correct: flushSync in event handlers is safe
flushSync(() => {
setSomething(newValue);
});
}
```
--------------------------------
### Read Context with `use` hook
Source: https://ko.react.dev/reference/react/use
Use the `use` hook to read the value from a Context. This hook behaves like `useContext` but can be called within conditional logic.
```javascript
import { use } from 'react';
function Button() {
const theme = use(ThemeContext);
// ...
}
```
--------------------------------
### Handle Children with Fragments using Children.map
Source: https://ko.react.dev/reference/react/Children
Demonstrates that `Children.map` does not include the rendered output of internal components like fragments. The `RowList` component will only wrap the direct children passed to it, not the elements within a fragment.
```javascript
import RowList from './RowList.js';
export default function App() {
return (
This is the first item.
);
}
function MoreRows() {
return (
<>
This is the second item.
This is the third item.
>
);
}
```
```javascript
import { Children } from 'react';
export default function RowList({ children }) {
return (
{Children.map(children, child =>
{child}
)}
);
}
```
--------------------------------
### Wrap Each Child with a Div using Children.map
Source: https://ko.react.dev/reference/react/Children
Use `Children.map` to iterate over children and wrap each one in a `div` with the class `Row`. This is useful when you need to apply a common wrapper to all direct children.
```javascript
import { Children } from 'react';
function RowList({ children }) {
return (
{Children.map(children, child =>
{child}
)}
);
}
```
```javascript
This is the first item.
This is the second item.
This is the third item.
```
```javascript
This is the first item.
This is the second item.
This is the third item.
```
```javascript
import RowList from './RowList.js';
export default function App() {
return (
This is the first item.
This is the second item.
This is the third item.
);
}
```
```javascript
import { Children } from 'react';
export default function RowList({ children }) {
return (
{Children.map(children, child =>
{child}
)}
);
}
```
--------------------------------
### CSS Styling for Page Layout and Cards
Source: https://ko.react.dev/reference/react/Fragment
Provides styles for the page layout, including a transition for background color changes, filler elements to enable scrolling, and distinct styling for 'card' components to visually differentiate sections.
```css
.page {
transition: background 0.3s;
}
.filler {
height: 500px;
display: flex;
align-items: center;
justify-content: center;
color: #aaa;
font-size: 14px;
}
.card {
padding: 16px;
background: white;
border: 1px solid #ddd;
border-radius: 8px;
margin: 0 16px;
box-shadow: 0 1px 3px rgba(0,0,0,0.08);
font-weight: 600;
font-size: 14px;
}
.card.green {
border-left: 3px solid #28a745;
}
.card.blue {
border-left: 3px solid #007bff;
}
```
--------------------------------
### Action Function Signature with useActionState
Source: https://ko.react.dev/reference/react/useActionState
When using useActionState, the action function receives the previous state as the first argument and the form data as the second. This differs from standalone actions.
```javascript
// useActionState를 사용하지 않을 때
function action(formData) {
const name = formData.get('name');
}
```
```javascript
// useActionState를 사용할 때
function action(prevState, formData) {
const name = formData.get('name');
}
```
--------------------------------
### Defer flushSync to a Microtask
Source: https://ko.react.dev/reference/react-dom/flushSync
If moving `flushSync` to an event handler is difficult, deferring the call to a microtask allows the current render to complete before scheduling a synchronous flush.
```javascript
useEffect(() => {
// ✅ Correct: defer flushSync to a microtask
queueMicrotask(() => {
flushSync(() => {
setSomething(newValue);
});
});
}, []);
```
--------------------------------
### Correctly Calling dispatchAction with startTransition
Source: https://ko.react.dev/reference/react/useActionState
When manually calling dispatchAction outside of a form's action prop, wrap the call in startTransition to ensure isPending updates correctly.
```javascript
import { useActionState, startTransition } from 'react';
function MyComponent() {
const [state, dispatchAction, isPending] = useActionState(myAction, null);
function handleClick() {
// ✅ 올바른 방법: startTransition으로 감싸기
startTransition(() => {
dispatchAction();
});
}
// ...
```
--------------------------------
### Flush updates for third-party integrations with flushSync
Source: https://ko.react.dev/reference/react-dom/flushSync
When integrating with third-party code like browser APIs or UI libraries, you might need to force React to process updates. `flushSync` ensures that all state updates within the callback are processed synchronously, guaranteeing the DOM is updated before the next line of code executes. This is useful for browser APIs that expect the DOM to be updated synchronously.
```javascript
flushSync(() => {
setSomething(123);
});
// By this line, the DOM is updated.
```
--------------------------------
### Define static contextType for Class Components
Source: https://ko.react.dev/reference/react/Component
Specify the context to be read by this.context in a class component. The context must be created with createContext.
```javascript
class Button extends Component {
static contextType = ThemeContext;
render() {
const theme = this.context;
const className = 'button-' + theme;
return (
);
}
}
```
--------------------------------
### CSS for Cat Friends App
Source: https://ko.react.dev/reference/react/StrictMode
Basic CSS styling for the Cat Friends application, including layout for navigation, lists, and images.
```css
div {
width: 100%;
overflow: hidden;
}
nav {
text-align: center;
}
button {
margin: .25rem;
}
ul,
li {
list-style: none;
white-space: nowrap;
}
li {
display: inline;
padding: 0.5rem;
}
```
--------------------------------
### Shopping Cart App Component
Source: https://ko.react.dev/reference/react/useOptimistic
The main App component that manages the shopping cart state and provides action handlers. It uses `useState` for the cart and `startTransition` for smoother UI updates.
```javascript
import { useState, startTransition } from 'react';
import { addToCart, removeFromCart, updateQuantity } from './actions.js';
import ShoppingCart from './ShoppingCart';
export default function App() {
const [cart, setCart] = useState([]);
const cartActions = {
async add(item) {
await addToCart(item);
startTransition(() => {
setCart(current => {
const exists = current.find(i => i.id === item.id);
if (exists) {
return current.map(i =>
i.id === item.id ? { ...i, quantity: i.quantity + 1 } : i
);
}
return [...current, { ...item, quantity: 1 }];
});
});
},
async remove(id) {
await removeFromCart(id);
startTransition(() => {
setCart(current => current.filter(item => item.id !== id));
});
},
async updateQuantity(id, quantity) {
await updateQuantity(id, quantity);
startTransition(() => {
setCart(current =>
current.map(item =>
item.id === id ? { ...item, quantity } : item
)
);
});
}
};
return ;
}
```
--------------------------------
### compareDocumentPosition
Source: https://ko.react.dev/reference/react/Fragment
Compares the document position of the Fragment with another node, returning a bitmask that matches Node.compareDocumentPosition().
```APIDOC
## compareDocumentPosition(otherNode)
### Description
Compares the document position of the Fragment with another node, returning a bitmask matching the behavior of [`Node.compareDocumentPosition()`](https://developer.mozilla.org/en-US/docs/Web/API/Node/compareDocumentPosition).
### Method
`compareDocumentPosition`
### Parameters
#### Path Parameters
- **otherNode** (Node) - Required - The DOM node to compare against.
### Returns
A bitmask of [position flags](https://developer.mozilla.org/en-US/docs/Web/API/Node/compareDocumentPosition#return_value). Empty Fragments and Fragments with children rendered through a [portal](/reference/react-dom/createPortal) include `Node.DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC` in the result.
```