Amazing React 19 New Features !!!

Major changes in React

Published on May 30, 2024

Reading time: 2 minutes.


Example: Fetching Data with use To demonstrate the use hook, let’s create a simple example that fetches data from an API.

  1. Create a data fetching function:
1
2
3
4
5
const fetchData = async () => {
  const response = await fetch('https://jsonplaceholder.typicode.com/posts');
  const data = await response.json();
  return data;
};
  1. Use the use hook in your component:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
import React, { use } from 'react';

const DataFetchingComponent = () => {
  const data = use(fetchData());

  return (
    <div>
      <h1>Fetched Data</h1>
      <ul>
        {data.map((item) => (
          <li key={item.id}>{item.title}</li>
        ))}
      </ul>
    </div>
  );
};

export default DataFetchingComponent;

Key Points:

  1. Automatic Suspense Handling:

The use hook automatically suspends rendering until the promise passed to it resolves. This means you don’t need to manually manage loading states; React handles it for you.

  1. Server Components:

The use hook is particularly powerful in server components where data fetching can be done on the server before the HTML is sent to the client.

  1. Error Handling:

If the promise rejects, the use hook will propagate the error, and you can handle it using React’s error boundaries.

Complete Example with Error Handling:

  1. Create an error boundary component:
 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
import React from 'react';

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError(error) {
    return { hasError: true };
  }

  componentDidCatch(error, info) {
    console.error("Error occurred:", error, info);
  }

  render() {
    if (this.state.hasError) {
      return <h1>Something went wrong.</h1>;
    }
    return this.props.children;
  }
}

export default ErrorBoundary;
  1. Use the use hook with the error boundary:
 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
import React, { use } from 'react';
import ErrorBoundary from './ErrorBoundary';

const fetchData = async () => {
  const response = await fetch('https://jsonplaceholder.typicode.com/posts');
  if (!response.ok) {
    throw new Error('Network response was not ok');
  }
  const data = await response.json();
  return data;
};

const DataFetchingComponent = () => {
  const data = use(fetchData());

  return (
    <div>
      <h1>Fetched Data</h1>
      <ul>
        {data.map((item) => (
          <li key={item.id}>{item.title}</li>
        ))}
      </ul>
    </div>
  );
};

const App = () => (
  <ErrorBoundary>
    <DataFetchingComponent />
  </ErrorBoundary>
);

export default App;

In this complete example, we’ve added an error boundary to catch any errors that occur during data fetching and display a fallback UI. The use hook simplifies asynchronous data handling, making your components cleaner and more concise

Summary:

  • The use hook allows you to work with promises more naturally.
  • It suspends rendering until the promise resolves.
  • It integrates well with server components.
  • You can handle errors using React’s error boundaries.