React LogoReact 18 Features (Concurrent React, Automatic Batching, Transitions)

React 18 introduced a new concurrency framework that allows React to render multiple versions of the UI simultaneously. This isn't a "mode" that can be toggled on and off, but rather a new set of internal mechanisms that power new features and APIs. The primary goal is to improve the user experience by keeping the UI responsive even during intensive rendering tasks.

* Concurrent React: At its core, Concurrent React allows React to interrupt, pause, resume, and even cancel rendering. Previously, rendering was a single, uninterrupted, synchronous task. When a major update started, it would block the main thread until it completed, resulting in a "frozen" UI. With concurrency, React can prioritize urgent updates (e.g., writing input) over non-urgent ones (e.g., fetching search results), making the application feel faster and smoother.

* New Root API (`createRoot`): To use React 18's new synchronous features, applications must switch from `ReactDOM.render` to `ReactDOM.createRoot`. This new API configures your application to use the new synchronous renderer.
```javascript
// Pre-React 18
// import ReactDOM from 'react-dom';
// ReactDOM.render(<App />, document.getElementById('root'));

// React 18
import ReactDOM from 'react-dom/client';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);
```

* Automatic Batching: React 18 automatically batches multiple state updates into a single rerender, even outside of React event handlers (e.g., in promises, `setTimeout`, or native event handlers). This significantly reduces unnecessary rerendering and improves performance out of the box.
```javascript
// Before React 18, only onClick batched.
// fetchSomething().then(() => {
// setCount(c => c + 1); // Rerender
// setIsLoading(false); // Rerender
// });

// With React 18, both updates are batched into a single rerender.
// fetchSomething().then(() => {
// setCount(c => c + 1);
// setIsLoading(false);
// });
```

* Transitions (`useTransition` and `startTransition`):

* Concept: Transitions allow you to mark certain state updates as "non-urgent." React then prioritizes urgent updates (e.g., user input) over these non-urgent transitions. If an urgent update arrives while a transition is pending, React interrupts the transition, renders the urgent update, and then restarts the transition job in the background.
* `useTransition` Hook: This hook returns an array containing:

1. `isPending`: A boolean value indicating whether a transition is currently pending.

2. `startTransition`: A function that allows you to wrap state updates and mark them as transitions.

* `startTransition` (Imperative API): Used when you don't have a component context (e.g., in a library or framework) to wrap state updates.

* Benefit: Keeps the UI responsive. For example, when a user types in a search box, input is updated instantly, while potentially slow result filtering can occur in one pass, preventing the input field from feeling sluggish.

* `useDeferredValue` Hook: This hook allows you to defer re-rendering a non-urgent part of the UI. It takes a value and returns a "deferred" version of that value. When the original value changes, `useDeferredValue` waits a short time before updating its own value, giving React a chance to render more urgent updates first. This is similar to debouncing, but integrated into React's scheduler.
```javascript
const deferredSearchTerm = useDeferredValue(searchTerm);
// Use deferredSearchTerm for expensive filtering/rendering
```

* Strict Mode Enhancements: In React 18, Strict Mode binds and unbinds components, then rebinds them to the previous state. This helps uncover errors related to durable state and effects that can occur with concurrent rendering (for example, ensuring effects are idempotent and properly cleaned up).

* Server Components (Experimental/Future): While not a direct React 18 stable feature, they are a key part of the React team's vision. Server Components allow developers to create components that render solely on the server, potentially reducing client-side bundle size, improving initial page load performance, and improving SEO.

Example Code

```react
import React, { useState, useTransition } from 'react';
import ReactDOM from 'react-dom/client';

const generateItems = (query) => {
  const items = [];
  for (let i = 0; i < 10000; i++) {
    items.push(`Item ${i + 1} for "${query}"`);
  }
  return items;
};

function SearchResults({ query }) {
  const items = React.useMemo(() => generateItems(query), [query]);

  if (!query) {
    return <p>Start typing to see results.</p>;
  }

  // Büyük bir liste için yavaş bir render'ı simüle edin
  let startTime = performance.now();
  while (performance.now() - startTime < 5) {
    // Render işini simüle etmek için 5ms boyunca hiçbir şey yapmayın
  }

  return (
    <ul>
      {items.map((item, index) => (
        <li key={index}>{item}</li>
      ))}
    </ul>
  );
}

function App() {
  const [inputValue, setInputValue] = useState('');
  const [searchQuery, setSearchQuery] = useState('');
  const [isPending, startTransition] = useTransition();

  const handleChange = (e) => {
    setInputValue(e.target.value); // Giriş alanı için acil güncelleme

    // Arama sorgusu güncellemesini bir geçişe sarın
    // Bu, girişin anında güncellenmesini sağlarken, arama sonuçları
    // UI'ı engellemeden arka planda güncellenir.
    startTransition(() => {
      setSearchQuery(e.target.value);
    });
  };

  return (
    <div style={{ padding: '20px' }}>
      <h1>React 18 Geçişler Örneği</h1>
      <input
        type="text"
        value={inputValue}
        onChange={handleChange}
        placeholder="Öğeleri arayın..."
        style={{ width: '300px', padding: '8px' }}
      />
      {isPending && <p style={{ color: 'gray' }}>Sonuçlar yükleniyor...</p>}
      <div style={{ marginTop: '20px', maxHeight: '400px', overflowY: 'auto', border: '1px solid #eee' }}>
        <SearchResults query={searchQuery} />
      </div>
    </div>
  );
}

// React 18'in Yeni Kök API'si
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

// Bu kodu çalıştırmak için:
// 1. React 18'in kurulu olduğundan emin olun: npm install react react-dom
// 2. <div id="root"></div> içeren bir HTML dosyası olarak kaydedin veya bir React proje kurulumu kullanın (örn. Create React App, Vite).
```