What is React Fiber? What is the main goal of React Fiber?

👨‍💻 Frontend Developer 🟡 Often Asked 🎚️ Hard
#React

Brief Answer

React Fiber is a completely rewritten reconciliation architecture in React, introduced in version 16. The main goal of Fiber is to make React more responsive by enabling the ability to interrupt, pause, and resume the rendering algorithm.

Main goals of React Fiber:

  • Ability to interrupt rendering mid-process
  • Update prioritization (important updates run first)
  • Smooth animations and interactions
  • Improved UI responsiveness

What Fiber doesn’t do:

  • Doesn’t change React API
  • Doesn’t make applications faster in the usual sense
  • Doesn’t eliminate the need for optimization

Key advantage: Fiber allows React to “yield” CPU time to the browser for critical tasks like user input processing or animations! 🚀


Full Answer

Imagine you’re riding the subway. Old React is like a train that can’t stop between stations. React Fiber is like a train that can stop halfway, yield to an ambulance, and then continue moving! 🚇

What is React Fiber

React Fiber is React’s internal architecture, completely rewritten from scratch for more flexible rendering process management:

// Visualization of Fiber's work (simplified)
// Old React (Stack Reconciler):
// 1. Starts rendering
// 2. Can't stop until it finishes everything
// 3. Blocks the browser
 
// React Fiber (Fiber Reconciler):
// 1. Starts rendering
// 2. Can stop and yield time to the browser
// 3. Continues later
// 4. Doesn't block the browser

Main goal of React Fiber

The main goal of Fiber is to implement incremental rendering:

// Example of a problem Fiber solves
function HeavyComponent() {
  const [items, setItems] = useState([]);
  
  // Imagine this is a very heavy render
  const heavyRender = () => {
    const newItems = [];
    for (let i = 0; i < 10000; i++) {
      newItems.push({ id: i, value: `Item ${i}` });
    }
    setItems(newItems);
  };
  
  return (
    <div>
      <button onClick={heavyRender}>Create 10000 items</button>
      <div>
        {items.map(item => (
          <div key={item.id}>{item.value}</div>
        ))}
      </div>
    </div>
  );
}
 
// Without Fiber: button click blocks browser for several seconds
// With Fiber: rendering is&nbsp;split into parts, browser remains responsive

How React Fiber works

1. Update prioritization

Fiber can determine update priorities:

// Fiber distinguishes update types:
// 🔴 High priority: user input, animations
// 🟡 Normal priority: regular state updates
// 🟢 Low priority: background tasks, server data
 
function FiberPrioritization() {
  const [inputValue, setInputValue] = useState('');
  const [backgroundData, setBackgroundData] = useState([]);
  
  // User input - high priority
  const handleInputChange = (e) => {
    setInputValue(e.target.value); // Fiber processes this immediately
  };
  
  // Background data - low priority
  useEffect(() => {
    // Loading large volume of&nbsp;data
    fetchData().then(setBackgroundData); // Fiber can defer this
  }, []);
  
  return (
    <div>
      <input 
        value={inputValue} 
        onChange={handleInputChange}
        placeholder="Enter text..."
      />
      <div>
        {backgroundData.map(item => (
          <div key={item.id}>{item.name}</div>
        ))}
      </div>
    </div>
  );
}

2. Ability to interrupt

Fiber can interrupt rendering:

// Simplified example of&nbsp;Fiber's work
class FiberWorkLoop {
  // Fiber breaks work into units (units of&nbsp;work)
  performUnitOfWork() {
    // 1. Perform a&nbsp;small piece of&nbsp;work
    // 2. Check if&nbsp;browser has time
    if (shouldYield()) {
      // 3. If browser is&nbsp;busy - yield time to&nbsp;it
      return;
    }
    // 4. Continue work later
  }
}

Advantages of React Fiber

1. Increased responsiveness

// Without Fiber: blocking rendering
function BlockingRender() {
  const [count, setCount] = useState(0);
  
  const heavyOperation = () => {
    // This operation blocks the&nbsp;entire UI
    let result = 0;
    for (let i = 0; i < 1000000000; i++) {
      result += i;
    }
    setCount(result);
  };
  
  return (
    <div>
      <p>Counter: {count}</p>
      {/* Button click freezes UI for several seconds */}
      <button onClick={heavyOperation}>Heavy operation</button>
    </div>
  );
}
 
// With Fiber: non-blocking rendering
function NonBlockingRender() {
  const [count, setCount] = useState(0);
  
  const fiberOperation = () => {
    // Fiber breaks operation into parts
    // UI remains responsive
    setCount(prev => prev + 1);
  };
  
  return (
    <div>
      <p>Counter: {count}</p>
      {/* UI remains responsive even with frequent updates */}
      <button onClick={fiberOperation}>Operation with Fiber</button>
    </div>
  );
}

2. Better animations

// Fiber allows smooth handling of&nbsp;animations
function SmoothAnimation() {
  const [position, setPosition] = useState(0);
  
  // Animation will be&nbsp;smooth even with background updates
  useEffect(() => {
    const interval = setInterval(() => {
      setPosition(prev => (prev + 1) % 100);
    }, 16); // 60 FPS
    
    return () => clearInterval(interval);
  }, []);
  
  return (
    <div style={{ 
      transform: `translateX(${position}px)`,
      transition: 'transform 0.1s linear'
    }}>
      Smooth movement! 🚀
    </div>
  );
}

Common misconceptions

1. Fiber makes everything faster

// ❌ Misconception: Fiber automatically speeds up&nbsp;everything
// ✅ Reality: Fiber makes rendering interruptible
 
// Fiber doesn't reduce the&nbsp;amount of&nbsp;work, but&nbsp;makes it&nbsp;interruptible
// Total rendering time may even be&nbsp;longer!

2. Fiber is visible to developers

// ❌ Fiber doesn't change React API
// Developers don't interact with Fiber directly
 
// ✅ Fiber - internal implementation
// Everything remains the&nbsp;same for&nbsp;developers

Summary

React Fiber is like a smart air traffic controller! ✈️

  • Old React: like a plane that can’t change course mid-flight
  • React Fiber: like a controller who can redirect planes, yield to emergency flights, and optimize air traffic flow

Key advantage: Fiber makes React yielding - it can pause rendering to yield time to important browser tasks!

When this is useful:

  • Complex interfaces with many elements 📊
  • Applications with frequent data updates 📈
  • Interactive animations and transitions ✨

React Fiber is a fundamental rebuild that makes React more modern and adaptive to the requirements of modern web applications! 💪


Want more awesome React articles? Subscribe to EasyAdvice, bookmark the site and level up every day! 🚀