File size: 52,741 Bytes
25f22bf |
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 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 |
======================== CODE SNIPPETS ======================== TITLE: React Context API: Passing Dynamic Objects and Functions DESCRIPTION: This snippet illustrates passing a dynamic JavaScript object, containing both state (`currentUser`) and a function (`login`), as a context value. It highlights a common performance pitfall where creating a new object/function on every render causes unnecessary re-renders of consuming components, even if the underlying data hasn't changed. SOURCE: https://react.dev/reference/react/useContext LANGUAGE: JavaScript CODE: ``` function MyApp() { const [currentUser, setCurrentUser] = useState(null); function login(response) { storeCredentials(response.credentials); setCurrentUser(response.user); } return ( <AuthContext value={{ currentUser, login }}> <Page /> </AuthContext> ); } ``` ---------------------------------------- TITLE: Preventing Token Exposure with globalThis Lifetime DESCRIPTION: Illustrates how to use `experimental_taintUniqueValue` to protect a sensitive value, such as a user password, by tainting it for the entire application's lifetime using `globalThis`. SOURCE: https://react.dev/reference/react/experimental_taintUniqueValue LANGUAGE: JavaScript CODE: ``` import {experimental_taintUniqueValue} from 'react'; experimental_taintUniqueValue( 'Do not pass a user password to the client.', globalThis, process.env.SECRET_KEY ); ``` ---------------------------------------- TITLE: Securing getUser with experimental_taintObjectReference DESCRIPTION: This updated version of the `getUser` function demonstrates how to use React's `experimental_taintObjectReference` to prevent sensitive data leaks. By 'tainting' the user object, an error will be thrown if the entire object is inadvertently passed to a client component, enforcing data security. SOURCE: https://react.dev/reference/react/experimental_taintObjectReference LANGUAGE: JavaScript CODE: ``` // api.js import {experimental_taintObjectReference} from 'react'; export async function getUser(id) { const user = await db`SELECT * FROM users WHERE id = ${id}`; experimental_taintObjectReference( 'Do not pass the entire user object to the client. ' + 'Instead, pick off the specific properties you need for this use case.', user, ); return user; } ``` ---------------------------------------- TITLE: React experimental_taintUniqueValue API Reference DESCRIPTION: Documents the experimental `taintUniqueValue` API, which is designed to prevent sensitive, unique values (like passwords or tokens) from being inadvertently passed from Server Components to Client Components. This API is currently only available in experimental React versions and should not be used in production environments. It is specifically for use within React Server Components. SOURCE: https://react.dev/reference/react/experimental_taintUniqueValue LANGUAGE: APIDOC CODE: ``` taintUniqueValue(message, lifetime, value) Description: This API prevents unique values from being passed to Client Components, such as passwords, keys, or tokens. It is an experimental feature and is not available in stable React versions. It should only be used within React Server Components. Parameters: - message: (string) An error message that will be thrown if the tainted value is accessed in a Client Component. - lifetime: (string) Specifies the lifetime of the taint. The exact values and their meanings are part of the experimental API and typically relate to the scope of the taint (e.g., 'request', 'session'). - value: (any) The unique value to be tainted and prevented from being passed to Client Components. Usage Notes: - To use this API, React packages must be upgraded to the most recent experimental version (e.g., `react@experimental`, `react-dom@experimental`). - Experimental versions may contain bugs and are not suitable for production. - For preventing objects containing sensitive data, refer to `taintObjectReference`. Example Usage: // Prevent a token from being passed to Client Components // (Specific code example not provided in source, but conceptual usage is for securing tokens) ``` ---------------------------------------- TITLE: Secure Server-Side API Fetch with `server-only` DESCRIPTION: This snippet demonstrates the recommended secure practice for handling sensitive data. By importing `server-only`, this `fetchAPI` helper function is guaranteed to only run on the server. It directly accesses `process.env.API_PASSWORD` for authorization, ensuring the secret never leaves the server environment and is not bundled with client-side code. SOURCE: https://react.dev/reference/react/experimental_taintUniqueValue LANGUAGE: JavaScript CODE: ``` import "server-only"; export function fetchAPI(url) { const headers = { Authorization: process.env.API_PASSWORD }; return fetch(url, { headers }); } ``` ---------------------------------------- TITLE: Client Component Using Leaked Secret for Authorization DESCRIPTION: This Client Component (`Overview`) receives a `password` prop, which, if leaked from a Server Component, is then used directly in an `Authorization` header for a `fetch` request. This illustrates the consequence of the previous insecure pattern, where the client-side code now has access to and uses the sensitive secret. SOURCE: https://react.dev/reference/react/experimental_taintUniqueValue LANGUAGE: JavaScript CODE: ``` "use client"; import {useEffect} from '...' export async function Overview({ password }) { useEffect(() => { const headers = { Authorization: password }; fetch(url, { headers }).then(...); }, [password]); ... ``` ---------------------------------------- TITLE: Progressive Enhancement with useActionState Permalink DESCRIPTION: This example illustrates how to enable progressive enhancement for forms using `useActionState` by providing a permalink as the third argument. If the form is submitted before the JavaScript bundle loads, React will automatically redirect to the specified URL, ensuring basic functionality even without full client-side hydration. SOURCE: https://react.dev/reference/rsc/server-functions LANGUAGE: javascript CODE: ``` "use client"; import {updateName} from './actions'; function UpdateName() { const [, submitAction] = useActionState(updateName, null, `/name/update`); return ( <form action={submitAction}> ... </form> ); } ``` ---------------------------------------- TITLE: Tainting Sensitive Values with `experimental_taintUniqueValue` DESCRIPTION: This example shows how to use React's experimental `taintUniqueValue` API to proactively mark a sensitive value (like `process.env.API_PASSWORD`) as 'tainted'. If this tainted value is ever passed to a Client Component or sent to the client via a Server Function, React will throw an error with the specified message, providing an additional layer of protection against accidental secret leakage during refactoring or development. SOURCE: https://react.dev/reference/react/experimental_taintUniqueValue LANGUAGE: JavaScript CODE: ``` import "server-only"; import {experimental_taintUniqueValue} from 'react'; experimental_taintUniqueValue( 'Do not pass the API token password to the client. ' + 'Instead do all fetches on the server.', process, process.env.API_PASSWORD ); ``` ---------------------------------------- TITLE: Initial getUser Function for Database Access DESCRIPTION: This JavaScript function demonstrates a common pattern for fetching user data from a database. It directly returns the user object, which, if not handled carefully, could lead to sensitive data being exposed to client-side components. SOURCE: https://react.dev/reference/react/experimental_taintObjectReference LANGUAGE: JavaScript CODE: ``` // api.js export async function getUser(id) { const user = await db`SELECT * FROM users WHERE id = ${id}`; return user; } ``` ---------------------------------------- TITLE: Incorrectly Passing Secrets from Server to Client Component DESCRIPTION: This example demonstrates an insecure pattern where a sensitive environment variable (`process.env.API_PASSWORD`) is directly passed as a prop from a Server Component (`Dashboard`) to a Client Component (`Overview`). This action leaks the secret to the client, making it vulnerable. SOURCE: https://react.dev/reference/react/experimental_taintUniqueValue LANGUAGE: JavaScript CODE: ``` export async function Dashboard(props) { // DO NOT DO THIS return <Overview password={process.env.API_PASSWORD} />; } ``` ---------------------------------------- TITLE: Preventing User Data Leakage in React Server Components DESCRIPTION: Illustrates how to use `experimental_taintObjectReference` within a data fetching function (`getUser`) to prevent an entire user object, potentially containing sensitive data, from being passed to a React Client Component. It emphasizes the importance of explicitly selecting necessary properties for client-side use. SOURCE: https://react.dev/reference/react/experimental_taintObjectReference LANGUAGE: javascript CODE: ``` import {experimental_taintObjectReference} from 'react'; export async function getUser(id) { const user = await db`SELECT * FROM users WHERE id = ${id}`; experimental_taintObjectReference( 'Do not pass the entire user object to the client. ' + 'Instead, pick off the specific properties you need for this use case.', user, ); return user; } ``` ---------------------------------------- TITLE: React Client Component with useActionState for Progressive Enhancement DESCRIPTION: This example illustrates how to use `useActionState` with a third argument (a permalink) to enable progressive enhancement. If the JavaScript bundle hasn't loaded, submitting the form will redirect to the specified URL, ensuring basic functionality even before client-side hydration. SOURCE: https://react.dev/reference/rsc/server-actions LANGUAGE: JavaScript CODE: ``` "use client"; import {updateName} from './actions'; function UpdateName() { const [, submitAction] = useActionState(updateName, null, `/name/update`); return ( <form action={submitAction}> ... </form> ); } ``` ---------------------------------------- TITLE: React Effect for Page Visit Analytics DESCRIPTION: This snippet demonstrates using `useEffect` to log page visits. It highlights that in development mode, the effect might run twice due to React's Strict Mode, but this behavior is normal and does not affect production. It advises against trying to 'fix' the double call in development for analytics. SOURCE: https://react.dev/learn/synchronizing-with-effects LANGUAGE: JavaScript CODE: ``` useEffect(() => { logVisit(url); // Sends a POST request }, [url]); ``` ---------------------------------------- TITLE: React Server Function: Check Username Availability DESCRIPTION: This server-side function (`requestUsername`) processes form data to extract a username. It simulates a check for username availability and returns 'successful' or 'failed' based on a condition, demonstrating how server functions can provide direct feedback to the client. SOURCE: https://react.dev/reference/rsc/use-server LANGUAGE: JavaScript CODE: ``` 'use server'; export default async function requestUsername(formData) { const username = formData = formData.get('username'); if (canRequest(username)) { // ... return 'successful'; } return 'failed'; } ``` ---------------------------------------- TITLE: Display Pending State and Read Form Data with useFormStatus in React DESCRIPTION: This React component demonstrates how to use the `useFormStatus` hook to show a pending state during form submission and read the data being submitted. It disables the input and submit button while pending and displays the requested username from the form's `data` property. SOURCE: https://react.dev/reference/react-dom/hooks/useFormStatus LANGUAGE: javascript CODE: ``` import {useState, useMemo, useRef} from 'react'; import {useFormStatus} from 'react-dom'; export default function UsernameForm() { const {pending, data} = useFormStatus(); return ( <div> <h3>Request a Username: </h3> <input type="text" name="username" disabled={pending}/> <button type="submit" disabled={pending}> Submit </button> <br /> <p>{data ? `Requesting ${data?.get("username")}...`: ''}</p> </div> ); } ``` ---------------------------------------- TITLE: Caching Expensive Computations with `cache` for Shared Work DESCRIPTION: This example illustrates how `cache` can optimize performance by sharing results of expensive computations across different components. If `Profile` and `TeamReport` components both need metrics for the same `user` object, `cache` ensures that `calculateUserMetrics` is called only once for that user, and the result is shared, preventing duplicate work and improving efficiency. SOURCE: https://react.dev/reference/react/cache LANGUAGE: JavaScript CODE: ``` import {cache} from 'react'; import calculateUserMetrics from 'lib/user'; const getUserMetrics = cache(calculateUserMetrics); function Profile({user}) { const metrics = getUserMetrics(user); // ... } function TeamReport({users}) { for (let user in users) { const metrics = getUserMetrics(user); // ... } // ... } ``` ---------------------------------------- TITLE: React DOM Server APIs Reference DESCRIPTION: This section covers the APIs used for server-side rendering (SSR) in React DOM. These functions allow React components to be rendered to HTML strings or streams on the server. SOURCE: https://react.dev/reference/react/cache LANGUAGE: APIDOC CODE: ``` Server APIs: - renderToPipeableStream(element, options?): Renders a React tree to a Node.js Writable stream, allowing for streaming HTML responses. - renderToReadableStream(element, options?): Renders a React tree to a Web ReadableStream, suitable for environments like Cloudflare Workers or Deno. - renderToStaticMarkup(element): Renders a React element to its initial HTML. React will not add any React-specific attributes or extra DOM, and will not hydrate it on the client. - renderToString(element): Renders a React element to its initial HTML. React will attach event handlers to this markup on the client. ``` ---------------------------------------- TITLE: Correct React.cache Usage: Passing Primitive Arguments DESCRIPTION: This example demonstrates the correct way to use `React.cache` by passing primitive values as arguments. When primitives are passed, React's shallow equality check succeeds if the values are identical, ensuring that the memoized function only re-executes when its inputs truly change. SOURCE: https://react.dev/reference/react/cache LANGUAGE: javascript CODE: ``` import {cache} from 'react'; const calculateNorm = cache((x, y, z) => { // ... }); function MapMarker(props) { // ✅ Good: Pass primitives to memoized function const length = calculateNorm(props.x, props.y, props.z); // ... } function App() { return ( <> <MapMarker x={10} y={10} z={10} /> <MapMarker x={10} y={10} z={10} /> </> ); } ``` ---------------------------------------- TITLE: React DOM useFormStatus Hook for Form Status Access DESCRIPTION: The `useFormStatus` hook provides a convenient way for child components within a form to access the status of their parent `<form>`, such as its `pending` state. This eliminates the need for prop drilling, making it easier to build design components that react to form submission status. SOURCE: https://react.dev/blog/2024/04/25/react-19 LANGUAGE: javascript CODE: ``` import {useFormStatus} from 'react-dom'; function DesignButton() { const {pending} = useFormStatus(); return <button type="submit" disabled={pending} /> } ``` ---------------------------------------- TITLE: Demonstrate Multiple Instances of a Component with `useId` DESCRIPTION: This `App.js` example shows how a React component (`PasswordField`) that uses `useId` can be rendered multiple times within an application. The `useId` hook ensures that each instance of `PasswordField` generates unique IDs, preventing conflicts and maintaining accessibility. SOURCE: https://react.dev/reference/react/useId LANGUAGE: javascript CODE: ``` import { useId } from 'react'; function PasswordField() { const passwordHintId = useId(); return ( <> <label> Password: <input type="password" aria-describedby={passwordHintId} /> </label> <p id={passwordHintId}> The password should contain at least 18 characters </p> </> ); } export default function App() { return ( <> <h2>Choose password</h2> <PasswordField /> <h2>Confirm password</h2> <PasswordField /> </> ); } ``` ---------------------------------------- TITLE: Memoizing Expensive Computations with React `useMemo` DESCRIPTION: This snippet shows how `useMemo` is used in Client Components to cache the result of an expensive computation across renders. It ensures that if the dependencies (e.g., `record`) do not change, the computation is skipped, and the previously memoized value is returned. The cache is local to the component instance. SOURCE: https://react.dev/reference/react/cache LANGUAGE: JavaScript CODE: ``` 'use client'; function WeatherReport({record}) { const avgTemp = useMemo(() => calculateAvg(record), record); // ... } function App() { const record = getRecord(); return ( <> <WeatherReport record={record} /> <WeatherReport record={record} /> </> ); } ``` ---------------------------------------- TITLE: Server Function Form Submission with Hidden Fields DESCRIPTION: This snippet demonstrates how to use a Server Function (marked with `'use server'`) as the `action` for a React form. It shows how to pass additional data, such as a `productId`, to the server function using a hidden input field within the form, enabling progressive enhancement. SOURCE: https://react.dev/reference/react-dom/components/form LANGUAGE: JavaScript CODE: ``` import { updateCart } from './lib.js'; function AddToCart({productId}) { async function addToCart(formData) { 'use server' const productId = formData.get('productId') await updateCart(productId) } return ( <form action={addToCart}> <input type="hidden" name="productId" value={productId} /> <button type="submit">Add to Cart</button> </form> ); } ``` ---------------------------------------- TITLE: React Server Component Passing Full User Object to Client Component DESCRIPTION: This React Server Component illustrates a potential security vulnerability. It fetches a complete user object and then passes the entire object directly as a prop to a client-side `InfoCard` component, which is explicitly marked as an insecure practice. SOURCE: https://react.dev/reference/react/experimental_taintObjectReference LANGUAGE: JavaScript CODE: ``` import { getUser } from 'api.js'; import { InfoCard } from 'components.js'; export async function Profile(props) { const user = await getUser(props.userId); // DO NOT DO THIS return <InfoCard user={user} />; } ``` ---------------------------------------- TITLE: Complete React Component Using `useId` for Unique IDs DESCRIPTION: Provides a complete React functional component (`PasswordField`) that utilizes the `useId` hook to generate a unique ID for accessibility attributes. This ensures IDs do not clash when the component is rendered multiple times on the same page, making it suitable for reusable components. SOURCE: https://react.dev/reference/react/useId LANGUAGE: javascript CODE: ``` import { useId } from 'react'; function PasswordField() { const passwordHintId = useId(); return ( <> <label> Password: <input type="password" aria-describedby={passwordHintId} /> </label> <p id={passwordHintId}> The password should contain at least 18 characters </p> </> ); } ``` ---------------------------------------- TITLE: Tainting a Value Tied to an Object's Lifetime DESCRIPTION: Shows how to taint a value, like a user session token, where the taint's lifetime is bound to a specific object (e.g., a `user` object). This ensures the value remains protected as long as the encapsulating object exists. SOURCE: https://react.dev/reference/react/experimental_taintUniqueValue LANGUAGE: JavaScript CODE: ``` import {experimental_taintUniqueValue} from 'react'; export async function getUser(id) { const user = await db`SELECT * FROM users WHERE id = ${id}`; experimental_taintUniqueValue( 'Do not pass a user session token to the client.', user, user.session.token ); return user; } ``` ---------------------------------------- TITLE: React Server Function: Increment Like Count DESCRIPTION: This simple server-side function (`incrementLike`) demonstrates a basic operation that can be performed on the server. It increments a global `likeCount` variable and returns its updated value, showcasing how server functions can maintain and update state across client requests. SOURCE: https://react.dev/reference/rsc/use-server LANGUAGE: JavaScript CODE: ``` 'use server'; let likeCount = 0; export default async function incrementLike() { likeCount++; return likeCount; } ``` ---------------------------------------- TITLE: Legacy React APIs Reference DESCRIPTION: This section provides a reference to older or less commonly used APIs from the main 'react' package. While still available, newer patterns (like Hooks) are often preferred. SOURCE: https://react.dev/reference/react/cache LANGUAGE: APIDOC CODE: ``` Legacy React APIs: - Children: Utilities for working with the `props.children` opaque data structure. - cloneElement(element, props, ...children): Clones and returns a new React element using `element` as the starting point. - Component: The base class for defining React class components. - createElement(type, props, ...children): Creates and returns a new React element of the given type. - createRef(): Creates a ref that can be attached to a React element. - forwardRef(render): Creates a React component that forwards the ref attribute to a child component. - isValidElement(object): Verifies whether an object is a React element. - PureComponent: A base class for defining React class components that implements a shallow comparison for `shouldComponentUpdate`. ``` ---------------------------------------- TITLE: Correct useFormStatus Usage: Component Inside Form DESCRIPTION: Demonstrates the correct pattern for using `useFormStatus`, where the component calling the hook (`Submit`) is rendered as a child *inside* the `<form>`. This allows `useFormStatus` to correctly derive and return the `pending` status from its parent form. SOURCE: https://react.dev/reference/react-dom/hooks/useFormStatus LANGUAGE: javascript CODE: ``` function Submit() { // ✅ `pending` will be derived from the form that wraps the Submit component const { pending } = useFormStatus(); return <button disabled={pending}>...</button>; } function Form() { // This is the <form> `useFormStatus` tracks return ( <form action={submit}> <Submit /> </form> ); } ``` ---------------------------------------- TITLE: Server Functions with Manual Actions and useTransition DESCRIPTION: This example demonstrates how to integrate a server function with React's action pattern, specifically using `useTransition` to manage pending states. A server function is defined to update user data, and a client component wraps its invocation within `startTransition` to track loading states and handle potential errors. SOURCE: https://react.dev/reference/rsc/server-actions LANGUAGE: JavaScript CODE: ``` "use server"; export async function updateName(name) { if (!name) { return {error: 'Name is required'}; } await db.users.updateName(name); } ``` LANGUAGE: JavaScript CODE: ``` "use client"; import {updateName} from './actions'; import {useState, useTransition} from 'react'; function UpdateName() { const [name, setName] = useState(''); const [error, setError] = useState(null); const [isPending, startTransition] = useTransition(); const submitAction = async () => { startTransition(async () => { const {error} = await updateName(name); if (error) { setError(error); } else { setName(''); } }) } return ( <form action={submitAction}> <input type="text" name="name" disabled={isPending}/> {error && <span>Failed: {error}</span>} </form> ) } ``` ---------------------------------------- TITLE: Cache Function for React Server Components DESCRIPTION: The `cache` function is designed for use with React Server Components to memoize the result of a data fetch or computation. It helps optimize performance by preventing redundant executions of expensive operations. SOURCE: https://react.dev/reference/react/cache LANGUAGE: APIDOC CODE: ``` cache(fn): - Purpose: Caches the result of a function call. - Parameters: - fn: The function whose result is to be cached. This function should be pure and deterministic. - Returns: A memoized version of the input function `fn`. - Usage: - Cache an expensive computation: Prevents re-running CPU-intensive calculations. - Share a snapshot of data: Ensures all callers get the same data instance within a request. - Preload data: Can be used to fetch data once and reuse it across multiple components. - Note: `cache` is only for use with React Server Components. ``` ---------------------------------------- TITLE: Basic Usage of React `cache` for Function Memoization DESCRIPTION: This snippet demonstrates the fundamental usage of the `cache` function from React. It shows how to wrap an expensive computation function (`calculateMetrics`) with `cache` to create a memoized version (`getMetrics`). When `getMetrics` is called with specific data, it computes and caches the result, returning the cached value for subsequent calls with the same data, thus avoiding redundant computations. SOURCE: https://react.dev/reference/react/cache LANGUAGE: JavaScript CODE: ``` import {cache} from 'react'; import calculateMetrics from 'lib/metrics'; const getMetrics = cache(calculateMetrics); function Chart({data}) { const report = getMetrics(data); // ... } ``` ---------------------------------------- TITLE: React `useEffect` with `experimental_useEffectEvent` for Controlled Re-runs DESCRIPTION: This snippet demonstrates how to use the experimental `useEffectEvent` hook to prevent unwanted re-runs of a `useEffect`. By moving the `showNotification` logic into an `useEffectEvent`, the `theme` dependency is removed from the main `useEffect`, ensuring the chat connection only re-establishes when `roomId` changes. SOURCE: https://react.dev/learn/escape-hatches LANGUAGE: javascript CODE: ``` import { useState, useEffect } from 'react'; import { experimental_useEffectEvent as useEffectEvent } from 'react'; import { createConnection, sendMessage } from './chat.js'; import { showNotification } from './notifications.js'; const serverUrl = 'https://localhost:1234'; function ChatRoom({ roomId, theme }) { const onConnected = useEffectEvent(() => { showNotification('Connected!', theme); }); useEffect(() => { const connection = createConnection(serverUrl, roomId); connection.on('connected', () => { onConnected(); }); connection.connect(); return () => connection.disconnect(); }, [roomId]); return <h1>Welcome to the {roomId} room!</h1> } export default function App() { const [roomId, setRoomId] = useState('general'); const [isDark, setIsDark] = useState(false); return ( <> <label> Choose the chat room:{' '} <select value={roomId} onChange={e => setRoomId(e.target.value)} > <option value="general">general</option> <option value="travel">travel</option> <option value="music">music</option> </select> </label> <label> <input type="checkbox" checked={isDark} onChange={e => setIsDark(e.target.checked)} /> Use dark theme </label> <hr /> <ChatRoom roomId={roomId} theme={isDark ? 'dark' : 'light'} /> </> ); } ``` ---------------------------------------- TITLE: React Client Component: Calling Server Function with useTransition DESCRIPTION: This React client component (`LikeButton`) illustrates how to call a server function (`incrementLike`) outside of a standard HTML form. It uses `useTransition` to manage the pending state during the asynchronous server function call, allowing for UI updates like disabling a button and displaying a loading indicator. SOURCE: https://react.dev/reference/rsc/use-server LANGUAGE: JavaScript CODE: ``` import incrementLike from './actions'; import { useState, useTransition } from 'react'; function LikeButton() { const [isPending, startTransition] = useTransition(); const [likeCount, setLikeCount] = useState(0); const onClick = () => { startTransition(async () => { const currentCount = await incrementLike(); setLikeCount(currentCount); }); }; return ( <> <p>Total Likes: {likeCount}</p> <button onClick={onClick} disabled={isPending}>Like</button>; </> ); } ``` ---------------------------------------- TITLE: Wait for All Content to Load in React Server-Side Rendering for SEO/Crawlers DESCRIPTION: This JavaScript example shows how to ensure that all content is fully loaded before sending the HTML response, which is beneficial for web crawlers or static site generation. It leverages the `stream.allReady` Promise to await the completion of all rendering, allowing the server to send a complete HTML document rather than a progressive stream. SOURCE: https://react.dev/reference/react-dom/server/renderToReadableStream LANGUAGE: JavaScript CODE: ``` async function handler(request) { try { let didError = false; const stream = await renderToReadableStream(<App />, { bootstrapScripts: ['/main.js'], onError(error) { didError = true; console.error(error); logServerCrashReport(error); } }); let isCrawler = // ... depends on your bot detection strategy ... if (isCrawler) { await stream.allReady; } return new Response(stream, { status: didError ? 500 : 200, headers: { 'content-type': 'text/html' }, }); } catch (error) { return new Response('<h1>Something went wrong</h1>', { status: 500, headers: { 'content-type': 'text/html' }, }); } } ``` ---------------------------------------- TITLE: Incorrect useFormStatus Usage: Same Component Form Tracking DESCRIPTION: Illustrates a common pitfall where `useFormStatus` is called within the same component that renders the `<form>` it intends to track. This is incorrect because `useFormStatus` only tracks status information for a *parent* `<form>`, meaning `pending` will never be true in this scenario. SOURCE: https://react.dev/reference/react-dom/hooks/useFormStatus LANGUAGE: javascript CODE: ``` function Form() { // 🚩 `pending` will never be true // useFormStatus does not track the form rendered in this component const { pending } = useFormStatus(); return <form action={submit}></form>; } ``` ---------------------------------------- TITLE: Memoizing Expensive Calculations with React useMemo Hook DESCRIPTION: This code demonstrates how to use the `useMemo` hook to cache the result of an expensive calculation, `getFilteredTodos`. The calculation will only re-run if `todos` or `filter` (dependencies) change, preventing unnecessary re-computation on unrelated state updates and improving performance. SOURCE: https://react.dev/learn/you-might-not-need-an-effect LANGUAGE: javascript CODE: ``` import { useMemo, useState } from 'react'; function TodoList({ todos, filter }) { const [newTodo, setNewTodo] = useState(''); const visibleTodos = useMemo(() => { // ✅ Does not re-run unless todos or filter change return getFilteredTodos(todos, filter); }, [todos, filter]); // ... } ``` ---------------------------------------- TITLE: React DOM Client APIs Reference DESCRIPTION: This section details the APIs specifically designed for client-side rendering and hydration in React DOM. These functions are used to mount and update React applications in a browser environment. SOURCE: https://react.dev/reference/react/cache LANGUAGE: APIDOC CODE: ``` Client APIs: - createRoot(domNode, options?): Creates a React root for displaying content in a browser DOM node. This is the entry point for client-side rendering with React 18+. - hydrateRoot(domNode, reactNode, options?): Hydrates a React root that was previously rendered on the server, attaching event listeners and making it interactive. ``` ---------------------------------------- TITLE: React `experimental_taintUniqueValue` API Reference DESCRIPTION: The `experimental_taintUniqueValue` function is a React API used to mark a specific value as 'tainted'. If this tainted value is ever passed to a Client Component or sent to the client via a Server Function, React will throw an error, preventing accidental data leakage. This is particularly useful for protecting sensitive server-side data. SOURCE: https://react.dev/reference/react/experimental_taintUniqueValue LANGUAGE: APIDOC CODE: ``` taintUniqueValue(message: string, lifetime: any, value: any) Parameters: - message: string A descriptive error message that will be thrown if the tainted value is passed to the client. - lifetime: any An object that defines the 'lifetime' or scope of the tainted value. If this object is garbage collected, the taint is removed. Typically, `process` or a specific module object is used. - value: any The specific value to be tainted (e.g., a secret API key, a password). Returns: - void Usage Notes: - This API is experimental and subject to change. - It should be used on the server-side to protect values that must never reach the client. - The error is thrown at runtime when the tainted value is detected crossing the server-client boundary. ``` ---------------------------------------- TITLE: React Profile Page with Suspense for Posts DESCRIPTION: This example demonstrates how to wrap a potentially slow-loading component (`Posts`) with a `<Suspense>` boundary. React will stream the HTML for the `PostsGlimmer` fallback initially, then replace it with the actual `Posts` content once its data is loaded, improving perceived performance. SOURCE: https://react.dev/reference/react-dom/server/renderToReadableStream LANGUAGE: javascript CODE: ``` function ProfilePage() { return ( <ProfileLayout> <ProfileCover /> <Sidebar> <Friends /> <Photos /> </Sidebar> <Suspense fallback={<PostsGlimmer />}> <Posts /> </Suspense> </ProfileLayout> ); } ``` ---------------------------------------- TITLE: React Client Component Displaying User Information DESCRIPTION: This is a simple React Client Component designed to display user information. It expects a `user` object as a prop and accesses its `name` property. In a secure application, this component should only receive the necessary, non-sensitive data. SOURCE: https://react.dev/reference/react/experimental_taintObjectReference LANGUAGE: JavaScript CODE: ``` // components.js "use client"; export async function InfoCard({ user }) { return <div>{user.name}</div>; } ``` ---------------------------------------- TITLE: Type-Safe Lazy Ref Initialization with Getter Function DESCRIPTION: For scenarios requiring type safety and avoiding null checks, this pattern wraps the lazy initialization logic within a getter function. The `playerRef` itself remains nullable, but the `getPlayer()` function ensures a non-null instance is always returned, making it easier to work with type checkers. SOURCE: https://react.dev/reference/react/useRef LANGUAGE: JavaScript CODE: ``` function Video() { const playerRef = useRef(null); function getPlayer() { if (playerRef.current !== null) { return playerRef.current; } const player = new VideoPlayer(); playerRef.current = player; return player; } // ... } ``` ---------------------------------------- TITLE: React DOM Static APIs Reference DESCRIPTION: This section lists APIs related to static rendering or pre-rendering, often used for generating static HTML files or for specific server-side rendering scenarios. SOURCE: https://react.dev/reference/react/cache LANGUAGE: APIDOC CODE: ``` Static APIs: - prerender(element, options?): Pre-renders a React tree to static HTML, typically used for static site generation. - prerenderToNodeStream(element, options?): Pre-renders a React tree to a Node.js stream for static output. ``` ---------------------------------------- TITLE: Sharing Memoized Data Fetches Across Server Components with React `cache` DESCRIPTION: This example demonstrates using React's `cache` in Server Components to memoize data fetches, allowing multiple components to share the same cached data. Unlike `useMemo`, `cache` is suitable for data fetching and enables different component instances to access a shared cache, preventing duplicate work for identical requests. SOURCE: https://react.dev/reference/react/cache LANGUAGE: JavaScript CODE: ``` const cachedFetchReport = cache(fetchReport); function WeatherReport({city}) { const report = cachedFetchReport(city); // ... } function App() { const city = "Los Angeles"; return ( <> <WeatherReport city={city} /> <WeatherReport city={city} /> </> ); } ``` ---------------------------------------- TITLE: Specify Global ID Prefix for Multiple React Apps on a Page DESCRIPTION: Illustrates how to use `identifierPrefix` with `createRoot` or `hydrateRoot` when rendering multiple independent React applications on the same page. This prevents ID clashes by ensuring all IDs generated by `useId` within an app start with a distinct, specified prefix. SOURCE: https://react.dev/reference/react/useId LANGUAGE: JavaScript CODE: ``` import { createRoot } from 'react-dom/client'; import App from './App.js'; import './styles.css'; const root1 = createRoot(document.getElementById('root1'), { identifierPrefix: 'my-first-app-' }); root1.render(<App />); const root2 = createRoot(document.getElementById('root2'), { identifierPrefix: 'my-second-app-' }); root2.render(<App />); ``` ---------------------------------------- TITLE: Adding Server Rendering Support to a React Hook DESCRIPTION: This snippet extends the `useOnlineStatus` hook to support server-side rendering by including a `getServerSnapshot` function as the third argument to `useSyncExternalStore`. The `getServerSnapshot` provides an initial snapshot value for server-generated HTML and client hydration, ensuring consistent behavior across environments. SOURCE: https://react.dev/reference/react/useSyncExternalStore LANGUAGE: javascript CODE: ``` import { useSyncExternalStore } from 'react'; export function useOnlineStatus() { const isOnline = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot); return isOnline; } function getSnapshot() { return navigator.onLine; } function getServerSnapshot() { return true; // Always show "Online" for server-generated HTML } function subscribe(callback) { // ... } ``` ---------------------------------------- TITLE: React App State Preservation with Activity DESCRIPTION: This snippet shows how to modify the previous `App` component to use `<Activity>` for state preservation. By wrapping the `<Home />` component with `<Activity>` and toggling its `mode` based on the URL, the state of `<Home />` is retained even when the user navigates away and then returns. SOURCE: https://react.dev/blog/2025/04/23/react-labs-view-transitions-activity-and-more LANGUAGE: JavaScript CODE: ``` function App() { const { url } = useRouter(); return ( <> <Activity mode={url === '/' ? 'visible' : 'hidden'}> <Home /> </Activity> {url !== '/' && <Details />} </> ); } ``` ---------------------------------------- TITLE: Integrating React Server Function with HTML Form Action DESCRIPTION: This JavaScript snippet demonstrates how to use a React Server Function directly as the 'action' handler for an HTML form. When the form is submitted, React automatically invokes the server function, passing the form's FormData object as its first argument. This pattern enables server-side data mutations with progressive enhancement, allowing the form to function even before the client-side JavaScript bundle loads. SOURCE: https://react.dev/reference/rsc/use-server LANGUAGE: JavaScript CODE: ``` // App.js async function requestUsername(formData) { 'use server'; const username = formData.get('username'); // ... } export default function App() { return ( <form action={requestUsername}> <input type="text" name="username" /> <button type="submit">Request</button> </form> ); } ``` ---------------------------------------- TITLE: React DOM HTML Elements Reference DESCRIPTION: This section provides a reference to common HTML elements that React DOM supports as components. These are standard HTML tags that can be used directly within JSX. SOURCE: https://react.dev/reference/react/cache LANGUAGE: APIDOC CODE: ``` Components: - Common (e.g. <div>): Standard HTML elements like div, span, p, etc. - <form>: HTML form element. - <input>: HTML input element. - <option>: HTML option element for select. - <progress>: HTML progress element. - <select>: HTML select element. - <textarea>: HTML textarea element. - <link>: HTML link element. - <meta>: HTML meta element. - <script>: HTML script element. - <style>: HTML style element. - <title>: HTML title element. ``` ---------------------------------------- TITLE: Incorrect React.cache Usage with Object Props (Shallow Equality Pitfall) DESCRIPTION: This snippet illustrates a common pitfall when using `React.cache` (or similar memoization techniques) with non-primitive arguments. Passing a new object reference (like the `props` object) on every render, even if its internal values are the same, causes the memoized function to re-run because React's shallow equality check (`Object.is`) fails. SOURCE: https://react.dev/reference/react/cache LANGUAGE: javascript CODE: ``` import {cache} from 'react'; const calculateNorm = cache((vector) => { // ... }); function MapMarker(props) { // 🚩 Wrong: props is an object that changes every render. const length = calculateNorm(props); // ... } function App() { return ( <> <MapMarker x={10} y={10} z={10} /> <MapMarker x={10} y={10} z={10} /> </> ); } ``` ---------------------------------------- TITLE: Implementing a useOnlineStatus Custom Hook with useDebugValue and useSyncExternalStore DESCRIPTION: A complete implementation of a `useOnlineStatus` custom hook that leverages `useSyncExternalStore` to subscribe to browser online/offline events and `useDebugValue` to provide a clear debug label in React DevTools. This hook returns the current online status. SOURCE: https://react.dev/reference/react/useDebugValue LANGUAGE: JavaScript CODE: ``` import { useSyncExternalStore, useDebugValue } from 'react'; export function useOnlineStatus() { const isOnline = useSyncExternalStore(subscribe, () => navigator.onLine, () => true); useDebugValue(isOnline ? 'Online' : 'Offline'); return isOnline; } function subscribe(callback) { window.addEventListener('online', callback); window.addEventListener('offline', callback); return () => { window.removeEventListener('online', callback); window.removeEventListener('offline', callback); }; } ``` ---------------------------------------- TITLE: React DOM Hooks Reference DESCRIPTION: This section lists the hooks available in React DOM, providing a quick reference to their names. Hooks are functions that let you 'hook into' React state and lifecycle features from function components. SOURCE: https://react.dev/reference/react/cache LANGUAGE: APIDOC CODE: ``` Hooks: - useFormStatus: Allows components to read the pending state of a form submission. ``` ---------------------------------------- TITLE: Consuming a shared memoized function in React components DESCRIPTION: These examples show how React components (`Temperature` and `Precipitation`) correctly import and utilize a shared memoized function. By calling the same memoized function from a central module, both components access the same cache, maximizing cache hits and reducing duplicate work when processing identical inputs. SOURCE: https://react.dev/reference/react/cache LANGUAGE: javascript CODE: ``` // Temperature.js import getWeekReport from './getWeekReport'; export default function Temperature({cityData}) { const report = getWeekReport(cityData); // ... } ``` LANGUAGE: javascript CODE: ``` // Precipitation.js import getWeekReport from './getWeekReport'; export default function Precipitation({cityData}) { const report = getWeekReport(cityData); // ... } ``` ---------------------------------------- TITLE: React Server Components: 'use server' Directive DESCRIPTION: The `'use server'` directive is used in React to mark functions or modules that are intended to run exclusively on the server. This enables server-side logic, such as database mutations or secure API calls, to be directly invoked from client components as Server Actions. SOURCE: https://react.dev/blog/2024/02/15/react-labs-what-we-have-been-working-on-february-2024 LANGUAGE: APIDOC CODE: ``` 'use server' - Purpose: Designates a function or an entire module to be executed on the server. - Usage: Placed at the top of a file to mark all exports as server functions, or at the top of a specific function body to mark only that function. - Context: Essential for creating Server Actions that can be passed to client components (e.g., as a form's `action` prop) and executed securely on the server. ``` ---------------------------------------- TITLE: Correct React.cache Usage: Passing Same Object Reference DESCRIPTION: This snippet shows another correct approach for using `React.cache` with objects. By ensuring that the same object reference is passed to the memoized function across renders (e.g., by defining it outside the component or memoizing it), React's shallow equality check will pass, allowing the memoized result to be reused. SOURCE: https://react.dev/reference/react/cache LANGUAGE: javascript CODE: ``` import {cache} from 'react'; const calculateNorm = cache((vector) => { // ... }); function MapMarker(props) { // ✅ Good: Pass the same `vector` object const length = calculateNorm(props.vector); // ... } function App() { const vector = [10, 10, 10]; return ( <> <MapMarker vector={vector} /> <MapMarker vector={vector} /> </> ); } ``` ---------------------------------------- TITLE: Reading External Store with React 19 use API DESCRIPTION: This snippet demonstrates the new `use` API introduced in React 19 for reading values from external stores. It is designed to integrate seamlessly with React's concurrent features, aiming to prevent tearing and avoid forcing bailouts from concurrent rendering, which was a limitation of `useSyncExternalStore`. SOURCE: https://react.dev/blog/2025/04/23/react-labs-view-transitions-activity-and-more LANGUAGE: JavaScript CODE: ``` const value = use(store); ``` ---------------------------------------- TITLE: React Server Components Directives DESCRIPTION: This section describes special directives used within React Server Components to define module boundaries and client/server code separation. These directives are crucial for building applications with React Server Components. SOURCE: https://react.dev/reference/react/cache LANGUAGE: APIDOC CODE: ``` Directives: - 'use client': Marks a module and its exports as client-side code, which will be bundled and executed on the client. - 'use server': Marks a module or function as server-side code, allowing it to be called from client components. ``` ---------------------------------------- TITLE: React Activity Component and Related APIs DESCRIPTION: This section details the behavior and best practices for using the React `Activity` component, especially concerning its `mode` prop and interaction with Server-Side Rendering (SSR). It also explains how `StrictMode` can help identify problematic side-effects and suggests `useDeferredValue` as an alternative for including hidden content in SSR. SOURCE: https://react.dev/reference/react/Activity LANGUAGE: APIDOC CODE: ``` Activity Component: - Concept: Behaves like 'unmounting' and 'remounting' a component, but saves React or DOM state. - Usage: - <Activity mode="visible" | "hidden">: Controls the visibility and lifecycle of its children. - mode="hidden": Content is not rendered during Server-Side Rendering (SSR). - Troubleshooting: - Effects don’t mount when an Activity is hidden: This is expected behavior as the component is conceptually 'unmounted'. - My hidden Activity is not rendered in SSR: Content within <Activity mode="hidden"> is excluded from SSR responses. Use `useDeferredValue` for deferred rendering if SSR inclusion is needed. StrictMode Component: - <StrictMode>: A development tool that helps identify unexpected side-effects. - Purpose: Eagerly performs Activity unmounts and mounts to catch problematic Effects. useDeferredValue Hook: - Purpose: Defers rendering of a value, allowing non-urgent updates to be rendered later. - Usage: Can be used as an alternative to <Activity mode="hidden"> if content needs to be included in the SSR response but rendered later on the client. ``` ---------------------------------------- TITLE: Wait for All Content to Load for Crawlers using React renderToPipeableStream DESCRIPTION: This snippet demonstrates how to use the `onAllReady` callback with `renderToPipeableStream` to ensure all content is fully loaded before sending the HTML response. This is particularly useful for crawlers or static site generation, allowing them to receive a complete page rather than a progressively streamed one, while regular users still benefit from streaming. SOURCE: https://react.dev/reference/react-dom/server/renderToPipeableStream LANGUAGE: javascript CODE: ``` let didError = false; let isCrawler = // ... depends on your bot detection strategy ... const { pipe } = renderToPipeableStream(<App />, { bootstrapScripts: ['/main.js'], onShellReady() { if (!isCrawler) { response.statusCode = didError ? 500 : 200; response.setHeader('content-type', 'text/html'); pipe(response); } }, onShellError(error) { response.statusCode = 500; response.setHeader('content-type', 'text/html'); response.send('<h1>Something went wrong</h1>'); }, onAllReady() { if (isCrawler) { response.statusCode = didError ? 500 : 200; response.setHeader('content-type', 'text/html'); pipe(response); } }, onError(error) { didError = true; console.error(error); logServerCrashReport(error); } }); ``` ---------------------------------------- TITLE: Global Application Initialization Logic DESCRIPTION: This example shows how to execute logic only once when the application starts, outside of React components. It includes a check for the `window` object to ensure the code runs specifically in a browser environment, suitable for tasks like checking authentication tokens or loading data from local storage. SOURCE: https://react.dev/learn/synchronizing-with-effects LANGUAGE: JavaScript CODE: ``` if (typeof window !== 'undefined') { // Check if we're running in the browser. checkAuthToken(); loadDataFromLocalStorage(); } function App() { // ... } ``` ---------------------------------------- TITLE: Basic React useFormStatus Hook Usage DESCRIPTION: Demonstrates how to import and use the `useFormStatus` hook within a React component to get the submission status of a parent form, disabling a button during the pending state. The `Submit` component must be rendered inside a `<form>` for the hook to function correctly. SOURCE: https://react.dev/reference/react-dom/hooks/useFormStatus LANGUAGE: javascript CODE: ``` import { useFormStatus } from "react-dom"; import action from './actions'; function Submit() { const status = useFormStatus(); return <button disabled={status.pending}>Submit</button> } export default function App() { return ( <form action={action}> <Submit /> </form> ); } ``` |