ReactWeb DevelopmentSoftware EngineeringSystems Design

WTF is React Fiber?

React Fiber has the buzzword vibe. In this article, I’ll attempt to unravel the mystery, explore its inner workings, and describe why it’s…

Table of Contents (10)

React Fiber has a buzzword vibe. It's React's reconciliation algorithm, and the code below puts the old approach next to Fiber so you can see what changed.

What is React Fiber?

React Fiber is the reconciliation algorithm introduced in React v16. It's a complete overhaul of React's core algorithm, and it determines how and when to update the DOM when the component tree changes.

Previously, React used a “stack” reconciliation algorithm that processed updates synchronously. That was fine for most cases but struggled with complex updates, animations, and user interactions.

Fiber introduces “fibers” as the units of work. React can break render functions into smaller chunks and prioritize them.

Key Features

  • Asynchronous Rendering: React can work on multiple tasks concurrently, so the main thread stays responsive during long renders.

  • Time-Slicing: React splits rendering work into small chunks and interleaves them with other tasks. High-priority updates, such as user interactions and animations, are processed quickly, and lower-priority updates can wait.

  • Suspense: Developers specify fallback content to display while data is fetched or components load.

  • Concurrent Mode (Experimental): React works on multiple tasks concurrently, which enables interruptible rendering and selective updates.

  • Error Boundaries: Error boundaries catch JavaScript errors in their child component tree, log them, and display a fallback UI, so one error doesn't crash the whole application.

Traditional React Reconciliation

Traditional reconciliation processes updates synchronously, which can leave the page unresponsive during complex rendering.

class App extends React.Component {
  state = { data: [] };

  componentDidMount() {
    // Fetch data and update state
    fetchData().then((data) => {
      this.setState({ data });
    });
  }

  render() {
    return (
      <div>
        {/* Render data */}
        {this.state.data.map((item) => (
          <div key={item.id}>{item.name}</div>
        ))}
      </div>
    );
  }
}

React Fiber with Suspense and Concurrent Mode

Fiber, combined with Suspense and Concurrent Mode, handles asynchronous rendering while keeping user interaction smooth.

import { Suspense } from 'react';

const DataComponent = React.lazy(() => import('./DataComponent'));

function App() {
  return (
    <div>
      <Suspense fallback={<div>Loading...</div>}>
        {/* Render data using lazy-loaded component */}
        <DataComponent />
      </Suspense>
    </div>
  );
}

// DataComponent.js
import React, { useState, useEffect } from 'react';

function DataComponent() {
  const [data, setData] = useState([]);

  useEffect(() => {
    // Fetch data and update state
    fetchData().then((fetchedData) => {
      setData(fetchedData);
    });
  }, []);

  return (
    <div>
      {/* Render data */}
      {data.map((item) => (
        <div key={item.id}>{item.name}</div>
      ))}
    </div>
  );
}

async function fetchData() {
  // Simulate data fetching
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve([{ id: 1, name: 'Item 1' }, { id: 2, name: 'Item 2' }]);
    }, 1000);
  });
}

export default DataComponent;

Here, React.lazy loads DataComponent and the Suspense component wraps it. The fallback prop specifies the content displayed while the data fetch or component rendering completes.

Traditional React Approach for Data Fetching

Traditional React applications typically fetch data in lifecycle methods such as componentDidMount. Developers fetch the data asynchronously and update the component's state with setState, which triggers a re-render and displays the data.

import React, { Component } from 'react';

class DataComponent extends Component {
  state = {
    data: null,
    isLoading: true,
    error: null,
  };

  componentDidMount() {
    // Fetch data asynchronously
    fetch('/api/data')
      .then((response) => {
        if (!response.ok) {
          throw new Error('Failed to fetch data');
        }
        return response.json();
      })
      .then((data) => {
        // Update state with fetched data and trigger re-render
        this.setState({ data, isLoading: false });
      })
      .catch((error) => {
        // Handle errors during data fetching
        this.setState({ error, isLoading: false });
      });
  }

  render() {
    const { data, isLoading, error } = this.state;

    if (isLoading) {
      return <div>Loading...</div>;
    }

    if (error) {
      return <div>Error: {error.message}</div>;
    }

    return (
      <div>
        {/* Render fetched data */}
        {data && data.map((item) => (
          <div key={item.id}>{item.name}</div>
        ))}
      </div>
    );
  }
}

export default DataComponent;

This works for simple cases but struggles with complex asynchronous operations and a smooth user experience. Fiber's Concurrent Mode, Suspense, and SuspenseList address those limits.

React Fiber with Suspense for Data Fetching

Suspense can also be used for data fetching, with fallback content shown while data loads.

import React, { useState, useEffect, Suspense } from 'react';

// Create a resource that reads data asynchronously
const createResource = (promise) => {
  let status = 'pending';
  let result;
  return {
    read() {
      if (status === 'pending') {
        throw promise;
      } else if (status === 'error') {
        throw result;
      } else if (status === 'success') {
        return result;
      }
    },
    resolve(data) {
      status = 'success';
      result = data;
    },
    reject(error) {
      status = 'error';
      result = error;
    },
  };
};

const fetchData = () => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve([{ id: 1, name: 'Item 1' }, { id: 2, name: 'Item 2' }]);
    }, 1000);
  });
};

const resource = createResource(fetchData());

resource.promise = fetchData()
  .then(resource.resolve)
  .catch(resource.reject);

function DataComponent() {
  const data = resource.read();
  return (
    <div>
      {/* Render data */}
      {data.map((item) => (
        <div key={item.id}>{item.name}</div>
      ))}
    </div>
  );
}

function App() {
  return (
    <div>
      <Suspense fallback={<div>Loading...</div>}>
        {/* Render data using Suspense */}
        <DataComponent />
      </Suspense>
    </div>
  );
}

export default App;

In this example, we use the componentDidMount lifecycle method to fetch data asynchronously and update the component's state. The isLoading state variable displays a loading indicator while the data is being fetched. Once the data is available, we render it.

That approach works for simple cases but has limits with complex asynchronous operations and a smooth user experience. Concurrent Mode, Suspense, and SuspenseList address them.

Traditional React Approach for Transitions

Traditional React applications often use CSS animations or third-party libraries like React Transition Group to create transitions between states. These approaches may not give the control and responsiveness modern applications need, particularly with complex rendering tasks or frequent updates.

import React, { Component } from 'react';
import './App.css';

class App extends Component {
  state = {
    show: false,
  };

  toggleShow = () => {
    this.setState((prevState) => ({ show: !prevState.show }));
  };

  render() {
    const { show } = this.state;

    return (
      <div className="App">
        <button onClick={this.toggleShow}>Toggle</button>
        <div className={`box ${show ? 'show' : 'hide'}`}>Content</div>
      </div>
    );
  }
}

export default App;
/* App.css */
.box {
  opacity: 0;
  transition: opacity 0.3s ease-in-out;
}

.box.show {
  opacity: 1;
}

.box.hide {
  opacity: 0;
}

React Fiber with Concurrent Mode and Transitions

Concurrent Mode lets React work on multiple tasks concurrently, which enables interruptible rendering and selective updates. It also makes smooth transitions between application states possible, as in this example:

import React, { useState, useTransition, Suspense } from 'react';

// ... (same as previous example)

function App() {
  const [resource, setResource] = useState(null);
  const [startTransition, isPending] = useTransition({ timeoutMs: 3000 });

  const handleClick = () => {
    const nextResource = createResource(fetchData());
    nextResource.promise = fetchData()
      .then(nextResource.resolve)
      .catch(nextResource.reject);
    startTransition(() => {
      setResource(nextResource);
    });
  };

  return (
    <div>
      <button onClick={handleClick}>Fetch Data</button>
      <Suspense fallback={<div>Loading...</div>}>
        {/* Render data using Suspense */}
        {resource && <DataComponent resource={resource} />}
      </Suspense>
      {isPending && <div>Loading...</div>}
    </div>
  );
}

export default App;

The useTransition hook keeps the interface responsive, even when fetching and rendering large amounts of data.

Traditional React Approach for Handling Multiple Asynchronous Operations

In traditional React applications, handling multiple asynchronous operations, such as fetching data for several components, often means managing the loading state for each one individually. Components may then show their loading indicators at different times, which makes for a disjointed and potentially confusing interface.

import React, { Component } from 'react';

class App extends Component {
  state = {
    data1: null,
    data2: null,
    loading1: true,
    loading2: true,
  };

  componentDidMount() {
    this.fetchData1();
    this.fetchData2();
  }

  fetchData1 = () => {
    setTimeout(() => {
      this.setState({ data1: 'Data 1', loading1: false });
    }, 1000);
  };

  fetchData2 = () => {
    setTimeout(() => {
      this.setState({ data2: 'Data 2', loading2: false });
    }, 2000);
  };

  render() {
    const { data1, data2, loading1, loading2 } = this.state;

    return (
      <div className="App">
        {loading1 ? <div>Loading item 1...</div> : <div>{data1}</div>}
        {loading2 ? <div>Loading item 2...</div> : <div>{data2}</div>}
      </div>
    );
  }
}

export default App;

In this example, we use the componentDidMount lifecycle method to fetch data for two components. The loading1 and loading2 state variables control the visibility of the loading indicators for each component. The data is fetched with simulated delays, and the loading indicators are displayed until the data is ready.

SuspenseList addresses this by coordinating the revealed order of multiple Suspense components.

Asynchronous Rendering with React Fiber’s SuspenseList

When several components wrapped in Suspense fetch data concurrently, SuspenseList coordinates the revealed order of the fallback content. That gives us control over how and when content is displayed.

import React, { Suspense, SuspenseList } from 'react';

// ... (same as previous examples)

function App() {
  return (
    <div>
      <SuspenseList revealOrder="forwards" tail="collapsed">
        <Suspense fallback={<div>Loading item 1...</div>}>
          <DataComponent resource={resource1} />
        </Suspense>
        <Suspense fallback={<div>Loading item 2...</div>}>
          <DataComponent resource={resource2} />
        </Suspense>
      </SuspenseList>
    </div>
  );
}

export default App;

In this example, we use the SuspenseList component to wrap two Suspense components. The revealOrder prop specifies the order in which the fallback content is revealed (“forwards” means from first to last), and the tail prop specifies how the tail items (items after the first one) should be displayed (“collapsed” means they are hidden until the first item is ready).

The official React documentation covers Fiber and its features in more detail: