DEV Community

Cover image for React.js ~use() hook Rules and Gotchas~
Ogasawara Kakeru
Ogasawara Kakeru

Posted on

React.js ~use() hook Rules and Gotchas~

use() can be called conditionally
Unlike every other hook, use() works inside if, for, and after early returns. React's linter is aware of this exception.

use() cannot be called in try-catch
Rejected promises are caught by Error Boundaries, not by try-catch blocks. If you wap use() in a try-catch, React throws a "Suspense Exception" error.

// This will crash
try {
  const data = use(promise);
} catch (e) {
  // Never reaches here
}
Enter fullscreen mode Exit fullscreen mode

If you need to provide a fallback value for a rejected promise, use .catch() on promise itself:

const safePromise = riskyFetch().catch(() => defaultValue);
const data = use(safePromise);
Enter fullscreen mode Exit fullscreen mode

Resolved values must be serialization(Server to Client)
When passing a promise from a Server Component to a Client Component, the resolved value must be serializable, no functions, no class instance, no symbols, plain objects, and arrays are fine.

Don't mix patterns for the same data
If you read a promise with use(), don't also fetch the same data in a useEffect. Pick one source of truth for each piece of data.

Top comments (0)