### Basic React App Setup Source: https://es.react.dev/reference/react/StrictMode Standard setup for a React application using createRoot from react-dom/client. ```javascript import { createRoot } from 'react-dom/client'; import './styles.css'; import App from './App'; const root = createRoot(document.getElementById("root")); root.render(); ``` -------------------------------- ### Start Streaming with onShellReady Source: https://es.react.dev/reference/react-dom/server/renderToPipeableStream This example demonstrates how to initiate the streaming of HTML to the client once the application shell has been rendered. The `onShellReady` callback is used to set the response headers and begin piping the response. ```javascript const { pipe } = renderToPipeableStream(, { bootstrapScripts: ['/main.js'], onShellReady() { response.setHeader('content-type', 'text/html'); pipe(response); } }); ``` -------------------------------- ### Example: Theme Context Source: https://es.react.dev/reference/react/useContext A complete example demonstrating how to create a context, provide a value, and consume it using useContext in different components. ```APIDOC ## Example: Theme Context ### Description This example shows a full implementation of context with `useContext`, including creating a context, providing a value, and consuming it in multiple components. ### Code ```javascript import { createContext, useContext } from 'react'; const ThemeContext = createContext(null); export default function MyApp() { return (
) } function Form() { return ( ); } function Panel({ title, children }) { const theme = useContext(ThemeContext); const className = 'panel-' + theme; return (

{title}

{children}
) } function Button({ children }) { const theme = useContext(ThemeContext); const className = 'button-' + theme; return ( ); } ``` ``` -------------------------------- ### Complete example using createElement Source: https://es.react.dev/reference/react/createElement A full example demonstrating how to create a React element and render a custom component using React.createElement(). ```javascript import { createElement } from 'react'; function Greeting({ name }) { return createElement( 'h1', { className: 'greeting' }, '¡Hola ', createElement('i', null, name), '. Bienvenido!' ); } export default function App() { return createElement( Greeting, { name: 'Taylor' } ); } ``` -------------------------------- ### Full Example: Theming with useContext Source: https://es.react.dev/reference/react/useContext This example demonstrates how to create a theme context, provide it, and consume it in multiple components (Panel and Button) to apply styles. ```javascript import { createContext, useContext } from 'react'; const ThemeContext = createContext(null); export default function MyApp() { return ( ) } function Form() { return ( ); } function Panel({ title, children }) { const theme = useContext(ThemeContext); const className = 'panel-' + theme; return (

{title}

{children}
) } function Button({ children }) { const theme = useContext(ThemeContext); const className = 'button-' + theme; return ( ); } ``` -------------------------------- ### Hydrate a React application with index.js Source: https://es.react.dev/reference/react-dom/client/hydrateRoot This example shows the complete setup for hydrating a React application using hydrateRoot in an index.js file, including necessary imports and the call to hydrateRoot. ```javascript import './styles.css'; import { hydrateRoot } from 'react-dom/client'; import App from './App.js'; hydrateRoot( document.getElementById('root'), ); ``` -------------------------------- ### Basic useActionState Example Source: https://es.react.dev/reference/react/useActionState A simple example demonstrating how to use useActionState to manage a counter. The state is updated when the 'Increment' button is clicked. ```javascript import { useActionState } from "react"; async function increment(previousState, formData) { return previousState + 1; } function StatefulForm({}) { const [state, formAction] = useActionState(increment, 0); return ( {state} ) } ``` -------------------------------- ### API Routes for Data Fetching Source: https://es.react.dev/reference/rsc/server-components Example of API routes set up to fetch data from a database. These routes handle GET requests for notes and authors by ID. ```javascript import db from './database'; app.get(`/api/notes/:id`, async (req, res) => { const note = await db.notes.get(id); res.send({note}); }); app.get(`/api/authors/:id`, async (req, res) => { const author = await db.authors.get(id); res.send({author}); }); ``` -------------------------------- ### Example: Linking Input with Description using useId Source: https://es.react.dev/reference/react/useId This example demonstrates how to use useId to generate a unique ID for an input's description, ensuring accessibility even when the component is used multiple times. ```javascript <>

``` ```javascript import { useId } from 'react'; function PasswordField() { const passwordHintId = useId(); return ( <>

The password should contain at least 18 characters

); } ``` -------------------------------- ### Basic Suspense Usage Example Source: https://es.react.dev/reference/react/Suspense This example demonstrates how to use the Suspense component to show a loading indicator (``) while a list of albums is being fetched and rendered by the `` component. Suspense will automatically switch from the fallback to the albums once they are ready. ```APIDOC ## Visualización de una interfaz alternativa mientras se carga el contenido ### Description This example shows how to wrap a component that fetches data with `` to display a fallback UI. React will render the `fallback` prop until the `children` component has finished loading its data and is ready to render. ### Code Example ```jsx import { Suspense } from 'react'; import Albums from './Albums.js'; export default function ArtistPage({ artist }) { return ( <>

{artist.name}

}> ); } function Loading() { return

🌀 Loading...

; } ``` ### Usage Notes Only data sources enabled for Suspense will trigger a Suspense component. This includes data fetching in frameworks like Relay and Next.js, code splitting with `lazy`, and reading cached promises with `use`. Suspense does not detect data fetching done within Effects or event handlers. ``` -------------------------------- ### Complete useReducer Example with Counter Source: https://es.react.dev/reference/react/useReducer A full example demonstrating a counter component using `useReducer`. It includes the reducer function, state initialization, and a button to dispatch an action to increment the age. ```javascript import { useReducer } from 'react'; function reducer(state, action) { if (action.type === 'incremented_age') { return { age: state.age + 1 }; } throw Error('Unknown action.'); } export default function Counter() { const [state, dispatch] = useReducer(reducer, { age: 42 }); return ( <>

¡Hola! Tú tienes {state.age}.

); } ``` -------------------------------- ### Example Usage of useEffect Source: https://es.react.dev/reference/react/useEffect This example demonstrates how to use `useEffect` to establish and disconnect a connection to an external chat system, managing the connection lifecycle based on `serverUrl` and `roomId` changes. ```APIDOC ```javascript import { useState, useEffect } from 'react'; import { createConnection } from './chat.js'; function ChatRoom({ roomId }) { const [serverUrl, setServerUrl] = useState('https://localhost:1234'); useEffect(() => { const connection = createConnection(serverUrl, roomId); connection.connect(); return () => { connection.disconnect(); }; }, [serverUrl, roomId]); // ... other component logic } ``` ``` -------------------------------- ### Counter Example with useState Source: https://es.react.dev/reference/react/useState This example demonstrates using `useState` to manage a number state for a counter. Clicking the button increments the count. ```javascript import { useState } from 'react'; export default function Counter() { const [count, setCount] = useState(0); function handleClick() { setCount(count + 1); } return ( ); } ``` -------------------------------- ### Basic useLayoutEffect Syntax Source: https://es.react.dev/reference/react/useLayoutEffect The basic syntax for useLayoutEffect. It takes a setup function and an optional dependencies array. ```javascript useLayoutEffect(setup, dependencies?) ``` -------------------------------- ### useLayoutEffect Example Source: https://es.react.dev/reference/react/useLayoutEffect An example demonstrating how to use useLayoutEffect to measure the height of an element before the browser repaints. ```APIDOC import { useState, useRef, useLayoutEffect } from 'react'; function Tooltip() { const ref = useRef(null); const [tooltipHeight, setTooltipHeight] = useState(0); useLayoutEffect(() => { const { height } = ref.current.getBoundingClientRect(); setTooltipHeight(height); }, []); // ... } ``` -------------------------------- ### Optimistic Form Update Example Source: https://es.react.dev/reference/react/useOptimistic An example demonstrating how to use useOptimistic for optimistic form updates, improving perceived performance by updating the UI immediately. ```APIDOC ## Optimistic Form Update ### Description The `useOptimistic` Hook provides an optimistic way to update the UI before a background operation completes, such as a network request. In the context of forms, this technique helps applications feel more responsive. When a user submits a form, instead of waiting for the server response to reflect changes, the UI updates immediately with the expected result. For example, when a user types a message in the form and then presses the 'Send' button, the `useOptimistic` Hook allows the message to appear immediately in the list with a 'Sending...' label, even before the message is sent to the server. This 'optimistic' approach gives the impression of speed and responsiveness. The form then attempts to actually send the message in the background. Once the server confirms the message has been received, the 'Sending...' label is removed. ### Code Example ```javascript import { useOptimistic, useState, useRef, startTransition } from "react"; import { deliverMessage } from "./actions.js"; function Thread({ messages, sendMessageAction }) { const formRef = useRef(); function formAction(formData) { addOptimisticMessage(formData.get("message")); formRef.current.reset(); startTransition(async () => { await sendMessageAction(formData); }); } const [optimisticMessages, addOptimisticMessage] = useOptimistic( messages, (state, newMessage) => [ { text: newMessage, sending: true }, ...state, ] ); return ( <>
{optimisticMessages.map((message, index) => (
{message.text} {!!message.sending && (Enviando...)}
))} ); } export default function App() { const [messages, setMessages] = useState([ { text: "¡Hola!", sending: false, key: 1 } ]); async function sendMessageAction(formData) { const sentMessage = await deliverMessage(formData.get("message")); startTransition(() => { setMessages((messages) => [{ text: sentMessage }, ...messages]); }) } return ; } ``` ``` -------------------------------- ### Lazy component example with dynamic import and delay Source: https://es.react.dev/reference/react/lazy This example demonstrates a lazy-loaded component with a simulated delay to observe the loading state. It uses `useState` to control the visibility of the preview and `Suspense` to show a `Loading` component while the `MarkdownPreview` is being fetched. ```javascript import { useState, Suspense, lazy } from 'react'; import Loading from './Loading.js'; const MarkdownPreview = lazy(() => delayForDemo(import('./MarkdownPreview.js'))); export default function MarkdownEditor() { const [showPreview, setShowPreview] = useState(false); const [markdown, setMarkdown] = useState('¡Hola, **mundo**!'); return ( <>