<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Guhaprasaanth Nandagopal</title>
    <description>The latest articles on DEV Community by Guhaprasaanth Nandagopal (@guhandelta).</description>
    <link>https://dev.to/guhandelta</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F425782%2Fe749de08-14e6-4b2b-8c0d-5fa791c43040.jpeg</url>
      <title>DEV Community: Guhaprasaanth Nandagopal</title>
      <link>https://dev.to/guhandelta</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/guhandelta"/>
    <language>en</language>
    <item>
      <title>Valtio: Unveiling the State Management Ninja with Bun and Vite</title>
      <dc:creator>Guhaprasaanth Nandagopal</dc:creator>
      <pubDate>Sat, 13 Jul 2024 04:03:48 +0000</pubDate>
      <link>https://dev.to/guhandelta/valtio-unveiling-the-state-management-ninja-with-bun-and-vite-3078</link>
      <guid>https://dev.to/guhandelta/valtio-unveiling-the-state-management-ninja-with-bun-and-vite-3078</guid>
      <description>&lt;h2&gt;
  
  
  Streamline Your State: Mastering Valtio with the Speed of Bun and Vite
&lt;/h2&gt;

&lt;p&gt;Managing the state of a React app is a crucial aspect of developing modern web applications. With the advent of new tools and libraries, developers can now efficiently handle state management with ease. This article explores how to manage state in a React app using Bun, Vite, and Valtio.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;About the Tools:&lt;br&gt;
Bun:&lt;/strong&gt;&lt;br&gt;
Bun is a modern JavaScript runtime that aims to be fast and efficient. It includes a bundler, a transpiler, and a package manager all in one. Bun is designed to be a drop-in replacement for Node.js and aims to improve developer productivity by reducing build times and improving performance.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Vite:&lt;/strong&gt;&lt;br&gt;
Vite is a build tool that offers an incredibly fast development experience for modern web projects. It leverages native ES modules in the browser and offers an optimized build process, making it ideal for modern JavaScript frameworks like React.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Valtio:&lt;/strong&gt;&lt;br&gt;
Valtio is a proxy-based state management library for React. It provides a simple and efficient way to manage and react to state changes, allowing developers to write less boilerplate code and focus on building features.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Purpose of Valtio:&lt;/strong&gt;&lt;br&gt;
The primary purpose of Valtio is to simplify state management in React applications by addressing several pain points commonly associated with other state management solutions. These pain points include:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Complexity and Boilerplate:&lt;/strong&gt;
Traditional state management libraries like Redux often require a significant amount of boilerplate code, including actions, reducers, and dispatch mechanisms. This can make the codebase cumbersome and difficult to maintain.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Valtio eliminates the need for such boilerplate by allowing direct manipulation of state objects. With Valtio, developers can work with plain JavaScript objects and use them directly in their React components.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Scalability and Performance:&lt;/strong&gt;
As applications grow in size and complexity, maintaining efficient and scalable state management becomes challenging. Performance issues can arise due to excessive re-renders and complex state dependencies.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Valtio uses proxies to create reactive state objects, ensuring that only the components dependent on the changed state are re-rendered. This leads to more efficient updates and better performance, even in large applications.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Intuitive API and Developer Experience:&lt;/strong&gt;
Learning and using state management libraries can have a steep learning curve, especially for new developers. The complexity of the API and the need to understand various concepts like reducers and middleware can be overwhelming.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Valtio offers an intuitive and straightforward API, making it easy for developers to get started. By leveraging familiar JavaScript concepts, Valtio reduces the learning curve and enhances the overall developer experience.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Motivation Behind Valtio:&lt;/strong&gt;&lt;br&gt;
The motivation behind Valtio stems from the need to address specific challenges and improve the state management experience for developers. Key motivations include:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Simplifying State Management:&lt;/strong&gt;&lt;br&gt;
The primary motivation behind Valtio is to simplify state management in React applications. By eliminating the need for boilerplate code and allowing direct state manipulation, Valtio makes it easier for developers to manage application state.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Enhancing Reactivity:&lt;/strong&gt;&lt;br&gt;
Valtio leverages JavaScript proxies to create reactive state objects. This approach ensures that state changes are automatically tracked, and only the relevant components are re-rendered. Enhancing reactivity improves application performance and reduces the complexity of managing state updates.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Improving Developer Productivity:&lt;/strong&gt;&lt;br&gt;
By providing a simple and intuitive API, Valtio aims to improve developer productivity. Developers can focus on building features rather than dealing with complex state management logic. This leads to faster development cycles and a more enjoyable development experience.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Supporting Modern React Applications:&lt;/strong&gt;&lt;br&gt;
Valtio is designed to work seamlessly with modern React features, including hooks and concurrent rendering. It aligns with the latest trends in React development, making it a suitable choice for modern web applications.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Features of Valtio:&lt;/strong&gt;&lt;br&gt;
Valtio offers several features that make it a compelling choice for state management in React applications:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Reactive State:&lt;/strong&gt;&lt;br&gt;
Valtio creates reactive state objects using JavaScript proxies. This ensures that state changes are automatically tracked and propagated to the relevant components.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Direct State Manipulation:&lt;/strong&gt;&lt;br&gt;
With Valtio, developers can directly manipulate state objects without the need for actions or reducers. This simplifies the codebase and reduces boilerplate.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Seamless Integration with React:&lt;/strong&gt;&lt;br&gt;
Valtio integrates seamlessly with React, supporting hooks and other modern React features. The useSnapshot hook allows components to subscribe to state changes effortlessly.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Derived State:&lt;/strong&gt;&lt;br&gt;
Valtio supports derived state, allowing developers to define computed values based on the state. This ensures that derived state values are always in sync with the underlying state.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Middleware and Plugins:&lt;/strong&gt;&lt;br&gt;
Valtio supports middleware and plugins, providing extensibility and allowing developers to add custom logic to state management.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Use Cases for Valtio:&lt;/strong&gt;&lt;br&gt;
Valtio is suitable for a wide range of use cases, including:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Simple State Management:&lt;/strong&gt;&lt;br&gt;
For small to medium-sized applications, Valtio offers a straightforward way to manage state without the overhead of more complex state management libraries.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Complex State Dependencies:&lt;/strong&gt;&lt;br&gt;
In applications with complex state dependencies, Valtio’s reactive state management ensures efficient updates and minimizes unnecessary re-renders.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Real-Time Applications:&lt;/strong&gt;&lt;br&gt;
For real-time applications that require frequent state updates, Valtio’s reactivity ensures that updates are propagated efficiently and components are kept in sync.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Rapid Prototyping:&lt;/strong&gt;&lt;br&gt;
Valtio’s simplicity and ease of use make it ideal for rapid prototyping, allowing developers to quickly build and test features.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Setting Up the Project:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 1:&lt;/strong&gt; &lt;strong&gt;Initialize the Project with Bun&lt;/strong&gt;&lt;br&gt;
First, ensure you have Bun installed. If not, you can install it from the official website.&lt;br&gt;
&lt;/p&gt;

&lt;pre class="highlight plaintext"&gt;&lt;code&gt;bun create react my-react-app
cd my-react-app
&lt;/code&gt;&lt;/pre&gt;



&lt;p&gt;&lt;strong&gt;Step 2:&lt;/strong&gt; &lt;strong&gt;Install Vite&lt;/strong&gt;&lt;br&gt;
Since Bun doesn’t natively support Vite out of the box, we’ll integrate it manually.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Install Vite and its dependencies:&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;pre class="highlight plaintext"&gt;&lt;code&gt;bun add vite @vitejs/plugin-react
&lt;/code&gt;&lt;/pre&gt;



&lt;ol&gt;
&lt;li&gt;
&lt;em&gt;Create a vite.config.js file at the root of your project:&lt;/em&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';

export default defineConfig({
  plugins: [react()],
});
&lt;/code&gt;&lt;/pre&gt;



&lt;p&gt;&lt;strong&gt;Step 3:&lt;/strong&gt; Set Up Valtio&lt;br&gt;
Install Valtio using Bun:&lt;br&gt;
&lt;/p&gt;

&lt;pre class="highlight plaintext"&gt;&lt;code&gt;bun add valtio
&lt;/code&gt;&lt;/pre&gt;



&lt;p&gt;&lt;strong&gt;Creating a Simple React App&lt;/strong&gt;&lt;br&gt;
Let’s create a simple React app that uses Valtio for state management. We’ll start with a counter example.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 4:&lt;/strong&gt; Create a React Component&lt;br&gt;
In the src directory, create a file named App.jsx:&lt;/p&gt;

&lt;p&gt;import React from 'react';&lt;br&gt;
import { useSnapshot } from 'valtio';&lt;br&gt;
import { proxy } from 'valtio';&lt;/p&gt;

&lt;p&gt;const state = proxy({&lt;br&gt;
  count: 0,&lt;br&gt;
});&lt;/p&gt;

&lt;p&gt;function App() {&lt;br&gt;
  const snap = useSnapshot(state);&lt;/p&gt;

&lt;p&gt;return (&lt;br&gt;
    &lt;/p&gt;
&lt;br&gt;
      &lt;h1&gt;Count: {snap.count}&lt;/h1&gt;
&lt;br&gt;
       state.count++}&amp;gt;Increment&lt;br&gt;
       state.count--}&amp;gt;Decrement&lt;br&gt;
    &lt;br&gt;
  );&lt;br&gt;
}

&lt;p&gt;export default App;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 5:&lt;/strong&gt; Update the Entry Point&lt;br&gt;
Update the main.jsx file to use Vite's hot module replacement (HMR) and render the App component:&lt;/p&gt;

&lt;p&gt;import React from 'react';&lt;br&gt;
import ReactDOM from 'react-dom/client';&lt;br&gt;
import App from './App';&lt;/p&gt;

&lt;p&gt;const root = ReactDOM.createRoot(document.getElementById('root'));&lt;br&gt;
root.render(&lt;br&gt;
  &lt;br&gt;
    &lt;br&gt;
  &lt;br&gt;
);&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Make sure your index.html file is set up correctly:&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&amp;lt;!DOCTYPE html&amp;gt;&lt;br&gt;
&lt;br&gt;
&lt;/p&gt;
&lt;br&gt;
  &lt;br&gt;
  &lt;br&gt;
  React App with Vite and Valtio&lt;br&gt;
&lt;br&gt;
&lt;br&gt;
  &lt;br&gt;
  &lt;br&gt;
&lt;br&gt;


&lt;p&gt;&lt;strong&gt;Step 6:&lt;/strong&gt; Start the Development Server&lt;br&gt;
Start your development server using Vite:&lt;/p&gt;

&lt;p&gt;bun vite&lt;/p&gt;

&lt;p&gt;This will start the Vite development server, and you should see your React app with the counter on &lt;a href="http://localhost:3000" rel="noopener noreferrer"&gt;http://localhost:3000&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Key Features of Valtio:&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Reactive State:&lt;/strong&gt; Automatically updates the UI when state changes.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Simplicity:&lt;/strong&gt; Minimal API that is easy to learn and use.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Derived State and Effects:&lt;/strong&gt; Supports derived state and side effects.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;TypeScript Support:&lt;/strong&gt; Excellent TypeScript support for type-safe state management.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Primary Components of Valtio&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;proxy&lt;/strong&gt;
The proxy function creates a reactive state object. It uses JavaScript Proxies to track changes and ensure that any state updates are automatically reflected in the UI.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Example:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { proxy } from 'valtio';

const state = proxy({
  count: 0,
  text: 'Hello, Valtio!'
});
&lt;/code&gt;&lt;/pre&gt;



&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;useSnapshot&lt;/strong&gt;
The useSnapshot hook subscribes to changes in the state and returns a snapshot of the state. This snapshot is automatically updated whenever the state changes, causing the component to re-render.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Example:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { useSnapshot } from 'valtio';

const Counter = () =&amp;gt; {
  const snap = useSnapshot(state);
  return (
    &amp;lt;div&amp;gt;
      &amp;lt;p&amp;gt;{snap.count}&amp;lt;/p&amp;gt;
      &amp;lt;button onClick={() =&amp;gt; state.count++}&amp;gt;Increment&amp;lt;/button&amp;gt;
    &amp;lt;/div&amp;gt;
  );
};
&lt;/code&gt;&lt;/pre&gt;



&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;subscribe&lt;/strong&gt;
The subscribe function allows subscribing to changes in the state without using React components. This is useful for logging, debugging, or triggering side effects outside of React components.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Example:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { subscribe } from 'valtio';

subscribe(state, () =&amp;gt; {
  console.log(`Count has changed to: ${state.count}`);
});
&lt;/code&gt;&lt;/pre&gt;



&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;derive&lt;/strong&gt;
The derive function creates derived state, which is computed from other state values. Derived state is automatically updated when the underlying state changes.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Example:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { derive } from 'valtio/utils';

const derivedState = derive({
  doubledCount: (get) =&amp;gt; get(state).count * 2
});
&lt;/code&gt;&lt;/pre&gt;



&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;devtools&lt;/strong&gt;
The devtools function integrates Valtio with browser developer tools for easier debugging and state inspection.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Example:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { devtools } from 'valtio/utils';

devtools(state, 'ValtioState');
&lt;/code&gt;&lt;/pre&gt;



&lt;p&gt;Putting It All Together: A Sample Application&lt;br&gt;
Let’s build a simple counter application to demonstrate how these components work together in a Valtio-based state management setup.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 1:&lt;/strong&gt; Setting Up the State&lt;br&gt;
&lt;/p&gt;

&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// state.js
import { proxy } from 'valtio';

export const state = proxy({
  count: 0,
  increment() {
    this.count++;
  },
  decrement() {
    this.count--;
  }
});
&lt;/code&gt;&lt;/pre&gt;



&lt;p&gt;&lt;strong&gt;Step 2:&lt;/strong&gt; Creating the Counter Component&lt;br&gt;
&lt;/p&gt;

&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Counter.js
import React from 'react';
import { useSnapshot } from 'valtio';
import { state } from './state';

const Counter = () =&amp;gt; {
  const snap = useSnapshot(state);

  return (
    &amp;lt;div&amp;gt;
      &amp;lt;p&amp;gt;Count: {snap.count}&amp;lt;/p&amp;gt;
      &amp;lt;button onClick={() =&amp;gt; state.increment()}&amp;gt;Increment&amp;lt;/button&amp;gt;
      &amp;lt;button onClick={() =&amp;gt; state.decrement()}&amp;gt;Decrement&amp;lt;/button&amp;gt;
    &amp;lt;/div&amp;gt;
  );
};

export default Counter;
&lt;/code&gt;&lt;/pre&gt;



&lt;p&gt;&lt;strong&gt;Step 3:&lt;/strong&gt; Integrating Derived State&lt;br&gt;
&lt;/p&gt;

&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// derivedState.js
import { derive } from 'valtio/utils';
import { state } from './state';

export const derivedState = derive({
  doubledCount: (get) =&amp;gt; get(state).count * 2
});
&lt;/code&gt;&lt;/pre&gt;



&lt;p&gt;&lt;strong&gt;Step 4:&lt;/strong&gt; Displaying Derived State&lt;br&gt;
&lt;/p&gt;

&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// DoubleCounter.js
import React from 'react';
import { useSnapshot } from 'valtio';
import { derivedState } from './derivedState';

const DoubleCounter = () =&amp;gt; {
  const snap = useSnapshot(derivedState);

  return (
    &amp;lt;div&amp;gt;
      &amp;lt;p&amp;gt;Doubled Count: {snap.doubledCount}&amp;lt;/p&amp;gt;
    &amp;lt;/div&amp;gt;
  );
};

export default DoubleCounter;
&lt;/code&gt;&lt;/pre&gt;



&lt;p&gt;&lt;strong&gt;Step 5:&lt;/strong&gt; Integrating DevTools&lt;br&gt;
&lt;/p&gt;

&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { devtools } from 'valtio/utils';
import { state } from './state';
import Counter from './Counter';
import DoubleCounter from './DoubleCounter';

devtools(state, 'ValtioState');

const App = () =&amp;gt; (
  &amp;lt;div&amp;gt;
    &amp;lt;h1&amp;gt;Valtio Counter App&amp;lt;/h1&amp;gt;
    &amp;lt;Counter /&amp;gt;
    &amp;lt;DoubleCounter /&amp;gt;
  &amp;lt;/div&amp;gt;
);

ReactDOM.render(&amp;lt;App /&amp;gt;, document.getElementById('root'));
&lt;/code&gt;&lt;/pre&gt;



&lt;p&gt;&lt;strong&gt;Flow Control in Managing UI Application’s State with Valtio:&lt;/strong&gt;&lt;br&gt;
Valtio is a modern state management library for React that leverages JavaScript Proxies to create reactive state objects. This article will delve into the flow control mechanisms in Valtio, explaining how it manages state changes, synchronizes state across components, and ensures optimal performance in a UI application.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Key Concepts in Valtio:&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Reactive State:&lt;/strong&gt; Valtio uses JavaScript Proxies to create reactive state objects, which automatically trigger re-renders in components when the state changes.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Proxies:&lt;/strong&gt; Proxies intercept interactions with state objects, allowing Valtio to track and manage state changes efficiently.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Snapshots:&lt;/strong&gt; Snapshots provide a way to use and observe the current state in React components.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Derived State:&lt;/strong&gt; Derived state allows the creation of computed values based on the reactive state.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Effects:&lt;/strong&gt; Effects enable executing side effects when the state changes.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Flow Control in Valtio:&lt;/strong&gt;&lt;br&gt;
The flow control in Valtio revolves around how state changes propagate through the application, ensuring that components stay in sync with the latest state. Here’s a detailed breakdown of the flow control process in Valtio:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;State Initialization&lt;/strong&gt;
State is initialized using the proxy function, which creates a reactive state object. This object will be used throughout the application to manage state changes.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Example:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { proxy } from 'valtio';

const state = proxy({
  count: 0,
  increment() {
    this.count++;
  },
  decrement() {
    this.count--;
  },
});

export default state;
&lt;/code&gt;&lt;/pre&gt;



&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;State Usage in Components&lt;/strong&gt;
React components use the useSnapshot hook to subscribe to state changes and get the current state. The useSnapshot hook ensures that components re-render automatically when the state changes.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Example:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React from 'react';
import { useSnapshot } from 'valtio';
import state from './state';

const Counter = () =&amp;gt; {
  const snap = useSnapshot(state);

  return (
    &amp;lt;div&amp;gt;
      &amp;lt;p&amp;gt;Count: {snap.count}&amp;lt;/p&amp;gt;
      &amp;lt;button onClick={() =&amp;gt; state.increment()}&amp;gt;Increment&amp;lt;/button&amp;gt;
      &amp;lt;button onClick={() =&amp;gt; state.decrement()}&amp;gt;Decrement&amp;lt;/button&amp;gt;
    &amp;lt;/div&amp;gt;
  );
};

export default Counter;
&lt;/code&gt;&lt;/pre&gt;



&lt;ol&gt;
&lt;li&gt;State Modification
State modifications are done directly on the state object. Valtio’s Proxy-based reactivity ensures that any changes to the state trigger re-renders in components that use the affected state.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Example:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;pre class="highlight plaintext"&gt;&lt;code&gt;state.increment(); // This will increment the count and trigger a re-render in subscribed components
&lt;/code&gt;&lt;/pre&gt;



&lt;ol&gt;
&lt;li&gt;Handling Asynchronous State Updates
Valtio supports asynchronous state updates seamlessly. You can define asynchronous functions within the state object to handle operations like data fetching.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Example:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { proxy } from 'valtio';

const asyncState = proxy({
  data: null,
  loading: false,
  error: null,
  async fetchData() {
    this.loading = true;
    this.error = null;
    try {
      const response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
      const result = await response.json();
      this.data = result;
    } catch (error) {
      this.error = error.message;
    } finally {
      this.loading = false;
    }
  }
});

export default asyncState;
&lt;/code&gt;&lt;/pre&gt;



&lt;ol&gt;
&lt;li&gt;Using Asynchronous State in Components
Components can use asynchronous state similarly to synchronous state. The useSnapshot hook will ensure that components re-render when the asynchronous state updates.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Example:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { useEffect } from 'react';
import { useSnapshot } from 'valtio';
import asyncState from './asyncState';

const DataComponent = () =&amp;gt; {
  const snap = useSnapshot(asyncState);

  useEffect(() =&amp;gt; {
    asyncState.fetchData();
  }, []);

  if (snap.loading) return &amp;lt;div&amp;gt;Loading...&amp;lt;/div&amp;gt;;
  if (snap.error) return &amp;lt;div&amp;gt;Error: {snap.error}&amp;lt;/div&amp;gt;;
  if (!snap.data) return null;

  return (
    &amp;lt;div&amp;gt;
      &amp;lt;p&amp;gt;Data: {snap.data.title}&amp;lt;/p&amp;gt;
    &amp;lt;/div&amp;gt;
  );
};

export default DataComponent;
&lt;/code&gt;&lt;/pre&gt;



&lt;ol&gt;
&lt;li&gt;Derived State and Effects
Derived state and effects provide additional mechanisms to manage state flow and side effects in Valtio.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Derived State: Derived state allows the creation of computed values based on the reactive state.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { derive } from 'valtio/utils';

const derivedState = derive({
  doubleCount: (get) =&amp;gt; get(state).count * 2,
});

export default derivedState;
&lt;/code&gt;&lt;/pre&gt;



&lt;p&gt;&lt;strong&gt;Using Derived State in Components:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React from 'react';
import { useSnapshot } from 'valtio';
import derivedState from './derivedState';

const DerivedComponent = () =&amp;gt; {
  const snap = useSnapshot(derivedState);

  return (
    &amp;lt;div&amp;gt;
      &amp;lt;p&amp;gt;Double Count: {snap.doubleCount}&amp;lt;/p&amp;gt;
    &amp;lt;/div&amp;gt;
  );
};

export default DerivedComponent;
&lt;/code&gt;&lt;/pre&gt;



&lt;p&gt;&lt;strong&gt;Effects: Effects enable executing side effects when state changes.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { subscribe } from 'valtio';

subscribe(state, () =&amp;gt; {
  console.log(`Count has changed to: ${state.count}`);
});
&lt;/code&gt;&lt;/pre&gt;



&lt;p&gt;&lt;strong&gt;Advanced State Management with Valtio:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 7:&lt;/strong&gt; Implement More Complex State Logic&lt;br&gt;
Valtio can handle more complex state logic. Let’s extend our example to include a to-do list.&lt;/p&gt;

&lt;p&gt;Update the App.jsx file:&lt;br&gt;
&lt;/p&gt;

&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React from 'react';
import { useSnapshot } from 'valtio';
import { proxy } from 'valtio';

const state = proxy({
  count: 0,
  todos: [],
});
function App() {
  const snap = useSnapshot(state);
  const addTodo = () =&amp;gt; {
    const newTodo = prompt('Enter a new to-do:');
    if (newTodo) {
      state.todos.push({ text: newTodo, done: false });
    }
  };
  return (
    &amp;lt;div&amp;gt;
      &amp;lt;h1&amp;gt;Count: {snap.count}&amp;lt;/h1&amp;gt;
      &amp;lt;button onClick={() =&amp;gt; state.count++}&amp;gt;Increment&amp;lt;/button&amp;gt;
      &amp;lt;button onClick={() =&amp;gt; state.count--}&amp;gt;Decrement&amp;lt;/button&amp;gt;
      &amp;lt;hr /&amp;gt;
      &amp;lt;h2&amp;gt;To-Do List&amp;lt;/h2&amp;gt;
      &amp;lt;button onClick={addTodo}&amp;gt;Add To-Do&amp;lt;/button&amp;gt;
      &amp;lt;ul&amp;gt;
        {snap.todos.map((todo, index) =&amp;gt; (
          &amp;lt;li key={index}&amp;gt;
            &amp;lt;input
              type="checkbox"
              checked={todo.done}
              onChange={() =&amp;gt; (state.todos[index].done = !todo.done)}
            /&amp;gt;
            {todo.text}
          &amp;lt;/li&amp;gt;
        ))}
      &amp;lt;/ul&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}
export default App;
&lt;/code&gt;&lt;/pre&gt;



&lt;p&gt;&lt;strong&gt;Step 8:&lt;/strong&gt; Managing Derived State&lt;br&gt;
Valtio allows you to create derived state using JavaScript getters. This can be useful for computed properties.&lt;br&gt;
&lt;strong&gt;Add a computed property to App.jsx:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const state = proxy({
  count: 0,
  todos: [],
  get completedTodos() {
    return this.todos.filter(todo =&amp;gt; todo.done).length;
  },
});

function App() {
  const snap = useSnapshot(state);
  const addTodo = () =&amp;gt; {
    const newTodo = prompt('Enter a new to-do:');
    if (newTodo) {
      state.todos.push({ text: newTodo, done: false });
    }
  };
  return (
    &amp;lt;div&amp;gt;
      &amp;lt;h1&amp;gt;Count: {snap.count}&amp;lt;/h1&amp;gt;
      &amp;lt;button onClick={() =&amp;gt; state.count++}&amp;gt;Increment&amp;lt;/button&amp;gt;
      &amp;lt;button onClick={() =&amp;gt; state.count--}&amp;gt;Decrement&amp;lt;/button&amp;gt;
      &amp;lt;hr /&amp;gt;
      &amp;lt;h2&amp;gt;To-Do List&amp;lt;/h2&amp;gt;
      &amp;lt;button onClick={addTodo}&amp;gt;Add To-Do&amp;lt;/button&amp;gt;
      &amp;lt;ul&amp;gt;
        {snap.todos.map((todo, index) =&amp;gt; (
          &amp;lt;li key={index}&amp;gt;
            &amp;lt;input
              type="checkbox"
              checked={todo.done}
              onChange={() =&amp;gt; (state.todos[index].done = !todo.done)}
            /&amp;gt;
            {todo.text}
          &amp;lt;/li&amp;gt;
        ))}
      &amp;lt;/ul&amp;gt;
      &amp;lt;p&amp;gt;Completed Todos: {snap.completedTodos}&amp;lt;/p&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}
export default App;
&lt;/code&gt;&lt;/pre&gt;



&lt;p&gt;&lt;strong&gt;Testing a Valtio-powered Component&lt;/strong&gt;&lt;br&gt;
Let’s consider a simple example:&lt;br&gt;
&lt;/p&gt;

&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { proxy, useSnapshot } from 'valtio';

const state = proxy({
  count: 0,
  increment() {
    state.count++;
  },
});

function Counter() {
  const snap = useSnapshot(state);
  return (
    &amp;lt;div&amp;gt;
      &amp;lt;p&amp;gt;Count: {snap.count}&amp;lt;/p&amp;gt;
      &amp;lt;button onClick={state.increment}&amp;gt;Increment&amp;lt;/button&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;



&lt;p&gt;Now, let’s write a unit test for it:&lt;br&gt;
&lt;/p&gt;

&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { render, screen, fireEvent } from '@testing-library/react';
import { proxy } from 'valtio';
import Counter from './Counter';

test('renders counter and increments count on button click', () =&amp;gt; {
  // Create a proxy for testing
  const state = proxy({ count: 0 });

  // Render the component with the test proxy
  render(&amp;lt;Counter state={state} /&amp;gt;);
  // Get references to the elements
  const countElement = screen.getByText(/Count: 0/i);
  const buttonElement = screen.getByRole('button');
  // Assert initial state
  expect(countElement).toBeInTheDocument();
  expect(countElement.textContent).toBe('Count: 0');
  // Simulate button click
  fireEvent.click(buttonElement);
  // Assert updated state
  expect(countElement.textContent).toBe('Count: 1');
});
&lt;/code&gt;&lt;/pre&gt;



&lt;p&gt;&lt;strong&gt;Key Points:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Create a Test Proxy&lt;/strong&gt;: Instead of using your production state, create a simple proxy specifically for testing.&lt;br&gt;
&lt;strong&gt;Provide the Proxy to Your Component&lt;/strong&gt;: Pass the state proxy as a prop to your Counter component.&lt;br&gt;
&lt;strong&gt;Test User Interactions&lt;/strong&gt;: Use RTL’s fireEvent to simulate user actions (like button clicks) and then assert that the UI updates as expected.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Best Practices&lt;/strong&gt;:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Focus on Behavior&lt;/strong&gt;: Test how the component behaves when its underlying Valtio state changes, rather than testing the internals of Valtio itself.&lt;br&gt;
&lt;strong&gt;Isolate Components&lt;/strong&gt;: If your component relies on other components that use Valtio, consider mocking those dependencies to keep your tests focused.&lt;br&gt;
&lt;strong&gt;Test Edge Cases&lt;/strong&gt;: Test scenarios like initial state, state updates, and error handling.&lt;br&gt;
&lt;strong&gt;Leverage RTL Utilities&lt;/strong&gt;: Utilize the full power of React Testing Library’s screen object and query methods for interacting with and asserting on your component's DOM.&lt;br&gt;
&lt;strong&gt;Detailed Comparison Table&lt;/strong&gt;:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;A closer look at how Valtio Differs from Other Libraries()&lt;/strong&gt;:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Reactive State Management
&lt;strong&gt;Valtio&lt;/strong&gt;: Valtio uses JavaScript Proxies to create reactive state objects. This means that any changes to the state automatically trigger re-renders of the components that use that state, without the need for explicit subscriptions or actions.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Other Libraries&lt;/strong&gt;:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Redux&lt;/strong&gt;: Uses a more traditional approach with actions and reducers to manage state changes. Requires boilerplate code for actions, reducers, and dispatching.&lt;br&gt;
&lt;strong&gt;MobX&lt;/strong&gt;: Uses observables to track state changes and reactions. While it provides automatic reactivity, it requires decorators or specific methods to define observables and actions.&lt;br&gt;
&lt;strong&gt;Zustand&lt;/strong&gt;: Uses hooks to manage state and provides a simple API. Reactivity is handled manually through hooks.&lt;br&gt;
&lt;strong&gt;Jotai&lt;/strong&gt;: This library uses atoms and hooks to manage state with a minimal API. Atom updates and hooks achieve reactivity.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;API Simplicity and Minimalism
&lt;strong&gt;Valtio&lt;/strong&gt;: Offers a very minimalistic API. The primary functions are proxy for creating reactive state objects and useSnapshot for using state within components.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Other Libraries&lt;/strong&gt;:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Redux&lt;/strong&gt;: The API is extensive, involving actions, reducers, middleware, and selectors. It can be overwhelming for new users due to its verbosity.&lt;br&gt;
&lt;strong&gt;MobX&lt;/strong&gt;: While powerful, MobX’s API includes observables, actions, reactions, and computed values, which can be complex to understand and use effectively.&lt;br&gt;
&lt;strong&gt;Zustand&lt;/strong&gt;: Provides a straightforward API but requires manual reactivity management through hooks.&lt;br&gt;
&lt;strong&gt;Jotai&lt;/strong&gt;: Also offers a minimal API with atoms and hooks, but the concept of atoms may introduce a slight learning curve.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Performance and Granular Updates
&lt;strong&gt;Valtio&lt;/strong&gt;: Valtio’s Proxy-based reactivity allows for fine-grained updates. Only the parts of the state that change will trigger re-renders, optimizing performance.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Other Libraries&lt;/strong&gt;:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Redux&lt;/strong&gt;: State updates can be optimized with selectors and middleware, but all updates go through the central store, which can introduce performance bottlenecks if not managed carefully.&lt;br&gt;
&lt;strong&gt;MobX&lt;/strong&gt;: Provides fine-grained reactivity through observables and reactions, making it very performant in handling complex state changes.&lt;br&gt;
&lt;strong&gt;Zustand&lt;/strong&gt;: Achieves good performance through hook-based state management but requires manual optimization for fine-grained updates.&lt;br&gt;
&lt;strong&gt;Jotai&lt;/strong&gt;: Allows for granular updates by splitting state into atoms, but managing many atoms can become complex.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;TypeScript Support
&lt;strong&gt;Valtio&lt;/strong&gt;: Has excellent TypeScript support, making it easy to define and use type-safe state objects.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Other Libraries&lt;/strong&gt;:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;** Redux*&lt;em&gt;: Provides strong TypeScript support, but the extensive boilerplate can make type definitions cumbersome.
**MobX&lt;/em&gt;*: Good TypeScript support, though decorators can complicate type definitions.&lt;/li&gt;
&lt;li&gt;** Zustand**: Offers good TypeScript support with simple type definitions.&lt;/li&gt;
&lt;li&gt;** Jotai**: Provides strong TypeScript support with straightforward type-safe atoms.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Conclusion:&lt;/strong&gt;&lt;br&gt;
Valtio’s simplicity and reactivity make it an excellent choice for state management in React applications. By combining Valtio with React Testing Library and Jest, you can ensure your state management logic is robust and reliable. This article has demonstrated how to set up and write unit tests for both synchronous and asynchronous Valtio states, providing a solid foundation for testing your Valtio-based state management.&lt;/p&gt;

</description>
      <category>react</category>
      <category>valtio</category>
      <category>bunjs</category>
      <category>vite</category>
    </item>
    <item>
      <title>Object-Based UI State Management vs. JavaScript Proxy-Based UI State Management</title>
      <dc:creator>Guhaprasaanth Nandagopal</dc:creator>
      <pubDate>Sat, 13 Jul 2024 02:33:56 +0000</pubDate>
      <link>https://dev.to/guhandelta/object-based-ui-state-management-vs-javascript-proxy-based-ui-state-management-58bk</link>
      <guid>https://dev.to/guhandelta/object-based-ui-state-management-vs-javascript-proxy-based-ui-state-management-58bk</guid>
      <description>&lt;p&gt;State management is a critical aspect of modern UI development, especially as applications grow in complexity. Two popular methods for managing UI state in JavaScript applications are object-based UI state management and proxy-based UI state management. Both approaches have their advantages and trade-offs. This article delves into these two methodologies, comparing their concepts, implementation, and practical use cases, using Redux and Zustand as examples.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Object-Based UI State Management:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Object-based state management involves managing the state using plain JavaScript objects. This method typically leverages libraries like Redux, MobX, or even the Context API in React. The core idea is to have a central store (an object) that holds the application’s state, and components subscribe to changes in this state.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Key Characteristics:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Centralized Store:&lt;/strong&gt; State is stored in a single or a few central objects.&lt;br&gt;
&lt;strong&gt;Immutable Updates:&lt;/strong&gt; State updates are performed immutably. Instead of modifying the existing state, a new state object is created and replaced.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Action-Based Changes:&lt;/strong&gt; State changes are triggered by dispatching actions (in libraries like Redux), which describe the changes to be made.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Selectors:&lt;/strong&gt; Functions that derive specific pieces of state from the central store, allowing components to subscribe to only the data they need.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Advantages:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Predictability:&lt;/strong&gt; Clear flow of data and state transitions make it easy to reason about the state changes.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Debugging:&lt;/strong&gt; Tools like Redux DevTools provide powerful debugging capabilities, showing the state before and after each action.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Testing:&lt;/strong&gt; The separation of actions and reducers (or similar constructs) facilitates easier unit testing.&lt;br&gt;
Disadvantages:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Boilerplate Code:&lt;/strong&gt; Often involves writing more code (actions, reducers, selectors), which can be verbose and cumbersome.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Performance:&lt;/strong&gt; Frequent state updates can lead to performance bottlenecks if not managed properly, especially in large applications.&lt;/p&gt;

&lt;p&gt;&lt;u&gt;Example with Redux:&lt;/u&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Redux Code Sample&lt;br&gt;
1)Installation:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install redux react-redux
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;2. Defining Actions:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// actions.js
export const INCREMENT = 'INCREMENT';
export const DECREMENT = 'DECREMENT';

export const increment = () =&amp;gt; ({
  type: INCREMENT
});

export const decrement = () =&amp;gt; ({
  type: DECREMENT
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;3. Creating Reducers:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// reducers.js
import { INCREMENT, DECREMENT } from './actions';

const initialState = {
  count: 0
};
const counterReducer = (state = initialState, action) =&amp;gt; {
  switch (action.type) {
    case INCREMENT:
      return { ...state, count: state.count + 1 };
    case DECREMENT:
      return { ...state, count: state.count - 1 };
    default:
      return state;
  }
};
export default counterReducer;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;4. Setting Up the Store&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// store.js
import { createStore } from 'redux';
import counterReducer from './reducers';

const store = createStore(counterReducer);
export default store;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;5. Connecting React Components&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// App.js
import React from 'react';
import { Provider, useSelector, useDispatch } from 'react-redux';
import store from './store';
import { increment, decrement } from './actions';

const Counter = () =&amp;gt; {
  const count = useSelector(state =&amp;gt; state.count);
  const dispatch = useDispatch();
  return (
    &amp;lt;div&amp;gt;
      &amp;lt;p&amp;gt;Count: {count}&amp;lt;/p&amp;gt;
      &amp;lt;button onClick={() =&amp;gt; dispatch(increment())}&amp;gt;Increment&amp;lt;/button&amp;gt;
      &amp;lt;button onClick={() =&amp;gt; dispatch(decrement())}&amp;gt;Decrement&amp;lt;/button&amp;gt;
    &amp;lt;/div&amp;gt;
  );
};
const App = () =&amp;gt; (
  &amp;lt;Provider store={store}&amp;gt;
    &amp;lt;Counter /&amp;gt;
  &amp;lt;/Provider&amp;gt;
);
export default App;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Proxy-Based UI State Management&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Proxy-based state management leverages the Proxy object in JavaScript, which allows for the creation of objects with custom behavior for fundamental operations like getting and setting properties. Libraries like Vue 3 (with its Composition API and reactive system) and Immer use Proxies to achieve reactivity and immutability.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Key Characteristics:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Reactive State:&lt;/strong&gt; State is made reactive by wrapping objects in a Proxy, which intercepts operations and triggers updates.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Transparent Mutations:&lt;/strong&gt; State can be mutated directly, and the Proxy ensures that the changes are tracked and propagated.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Minimal Boilerplate:&lt;/strong&gt; Direct mutations reduce the need for boilerplate code, making the development process more straightforward.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Advantages:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Simplicity:&lt;/strong&gt; Allows for direct state mutations, reducing the need for boilerplate code.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Reactivity:&lt;/strong&gt; Automatically tracks dependencies and updates, providing a responsive UI without manual subscription management.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Performance:&lt;/strong&gt; Efficiently tracks and updates only the parts of the state that change.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Disadvantages:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Complexity in Debugging:&lt;/strong&gt; Debugging can be more challenging due to the implicit nature of reactivity.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Learning Curve:&lt;/strong&gt; Understanding Proxies and their behavior can be more difficult for developers unfamiliar with this concept.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example with Valtio Composition API:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. Valtio Code Sample&lt;/strong&gt;&lt;br&gt;
Installation&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install valtio
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;2. Creating State&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// state.js
import { proxy } from 'valtio';

const state = proxy({
  count: 0
});
export default state;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;3. Creating Actions&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// actions.js
import state from './state';

export const increment = () =&amp;gt; {
  state.count += 1;
};
export const decrement = () =&amp;gt; {
  state.count -= 1;
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;4. Connecting React Components&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// App.js
import React from 'react';
import { useSnapshot } from 'valtio';
import state, { increment, decrement } from './state';

const Counter = () =&amp;gt; {
  const snap = useSnapshot(state);
  return (
    &amp;lt;div&amp;gt;
      &amp;lt;p&amp;gt;Count: {snap.count}&amp;lt;/p&amp;gt;
      &amp;lt;button onClick={increment}&amp;gt;Increment&amp;lt;/button&amp;gt;
      &amp;lt;button onClick={decrement}&amp;gt;Decrement&amp;lt;/button&amp;gt;
    &amp;lt;/div&amp;gt;
  );
};
const App = () =&amp;gt; &amp;lt;Counter /&amp;gt;;
export default App;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Comparison and Use Cases&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Predictability and Debugging:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Object-based state management offers better predictability and easier debugging with tools like Redux DevTools.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Proxy-based state management can be less predictable due to the implicit reactivity, making debugging more complex.&lt;br&gt;
Boilerplate and Development Speed:&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Object-based state management often requires more boilerplate code, which can slow down development.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Proxy-based state management simplifies the code by allowing direct mutations, speeding up the development process.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Performance:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Both methods can be performant if used correctly. Object-based management can suffer from performance issues if the state tree is large and frequently updated.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Proxy-based management can provide efficient updates by tracking only the necessary state changes.&lt;br&gt;
Learning Curve:&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Object-based state management may be easier for developers familiar with traditional Redux-like patterns.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Proxy-based state management, while powerful, requires understanding Proxies and reactive patterns, which can have a steeper learning curve.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Use Cases:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Object-Based:&lt;/strong&gt; Ideal for applications where state transitions need to be explicitly managed and debugged, such as complex enterprise applications.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Proxy-Based:&lt;/strong&gt; Suitable for applications where ease of state management and reactivity are prioritized, such as real-time data dashboards or interactive interfaces.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;br&gt;
Both Redux and Valtio offer powerful state management solutions with distinct advantages. Redux excels in predictability and tooling for complex applications, while Valtio provides simplicity and automatic reactivity for straightforward state management. Choosing the right tool depends on your application’s needs and your team’s familiarity with the respective libraries.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Remixed Relay: Evolution of React Server Component</title>
      <dc:creator>Guhaprasaanth Nandagopal</dc:creator>
      <pubDate>Fri, 12 Jul 2024 03:14:02 +0000</pubDate>
      <link>https://dev.to/guhandelta/evolution-of-react-server-componen-m8f</link>
      <guid>https://dev.to/guhandelta/evolution-of-react-server-componen-m8f</guid>
      <description>&lt;p&gt;&lt;strong&gt;React Server Components (RSC)&lt;/strong&gt; represents a significant advancement in how server-rendered content is handled in React applications. The concept of React Server Components draws inspiration from various previous technologies and patterns, particularly Relay. &lt;strong&gt;Relay&lt;/strong&gt; , a JavaScript framework for building data-driven React applications, provided foundational concepts that have influenced the development of React Server Components. This article delves into how React Server Components evolved from Relay, highlighting the similarities, differences, and advancements.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Understanding Relay&lt;br&gt;
What is Relay?&lt;/strong&gt;&lt;br&gt;
Relay is a JavaScript framework developed by Facebook (now Meta) for managing and fetching GraphQL data in React applications. It was designed to handle complex data requirements and provide a highly optimized data-fetching layer for React.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Key Features of Relay&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;GraphQL Integration:&lt;/strong&gt; Relay works seamlessly with GraphQL, allowing for precise data fetching and efficient updates.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Declarative Data Fetching:&lt;/strong&gt; Components declare their data dependencies using GraphQL fragments, making data requirements explicit and co-located with the components.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Optimistic Updates:&lt;/strong&gt; Relay supports optimistic UI updates, allowing the UI to reflect changes before the server confirms them.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Efficient Data Fetching:&lt;/strong&gt; Relay minimizes over-fetching and under-fetching by composing multiple data requirements into a single query.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The Concept of Server Components&lt;/strong&gt;&lt;br&gt;
What are React Server Components?&lt;br&gt;
React Server Components (RSC) allow developers to build components that run on the server and send HTML to the client. This approach aims to optimize server-side rendering (SSR) by splitting the rendering workload between the server and the client.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Key Features of React Server Components*&lt;br&gt;
Server-Side Execution:&lt;/strong&gt; Components can be executed on the server, reducing the client-side JavaScript bundle size.&lt;br&gt;
Direct Data Access: Server Components can directly access server-side data sources, such as databases or APIs, without additional client-side data fetching.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Seamless Integration:&lt;/strong&gt; RSC can be seamlessly integrated with client components, enabling a hybrid rendering model.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Improved Performance:&lt;/strong&gt; By offloading rendering to the server, React Server Components can improve the initial load performance and SEO.&lt;br&gt;
Evolution from Relay to React Server Components&lt;/p&gt;

&lt;p&gt;**Similarities:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Declarative Data Requirements&lt;/strong&gt;: Both Relay and React Server Components emphasize the declarative nature of data requirements. In Relay, components declare their GraphQL fragments, while in RSC, server components can directly fetch data and render HTML.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Optimized Data Fetching:&lt;/strong&gt; Relay’s efficient data fetching mechanism influenced RSC’s ability to directly access and fetch data on the server, reducing the need for multiple client-side requests.&lt;br&gt;
Component Co-location: In both Relay and RSC, data fetching logic is co-located with the components, making the data dependencies explicit and easier to manage.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Differences:&lt;br&gt;
Rendering Paradigm:&lt;/strong&gt; Relay focuses on optimizing client-side data fetching and updates using GraphQL, while React Server Components shift part of the rendering workload to the server, sending pre-rendered HTML to the client.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Server-Side Execution:&lt;/strong&gt; Relay operates entirely on the client side, fetching data and updating the UI. RSC executes components on the server, leveraging server resources to generate HTML and send it to the client.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Data Fetching:&lt;/strong&gt; Relay relies on GraphQL for data fetching, requiring a GraphQL server and schema. RSC can fetch data from any server-side data source, including REST APIs, databases, or other services, without being tied to GraphQL.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Advancements in React Server Components&lt;br&gt;
Simplified Data Access:&lt;/strong&gt; RSC simplifies data access by allowing server-side code to fetch data directly, avoiding the need for additional client-side data-fetching logic.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Reduced Client-Side Overhead:&lt;/strong&gt; By moving part of the rendering logic to the server, RSC reduces the amount of JavaScript that needs to be executed on the client, leading to improved performance and faster initial loads.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hybrid Rendering:&lt;/strong&gt; RSC supports a hybrid rendering model where server components can be combined with client components, providing flexibility in rendering strategies.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Improved SEO:&lt;/strong&gt; Server-side rendering with RSC improves SEO by delivering pre-rendered HTML content to search engines, making it easier for them to crawl and index the content.&lt;/p&gt;

&lt;p&gt;Example: Transition from Relay to React Server Components&lt;br&gt;
Relay Example&lt;br&gt;
import { graphql, QueryRenderer } from 'react-relay';&lt;br&gt;
import environment from './environment';&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const App = () =&amp;gt; (
  &amp;lt;QueryRenderer
    environment={environment}
    query={graphql`
      query AppQuery {
        user(id: "1") {
          name
        }
      }
    `}
    render={({ error, props }) =&amp;gt; {
      if (error) {
        return &amp;lt;div&amp;gt;Error!&amp;lt;/div&amp;gt;;
      }
      if (!props) {
        return &amp;lt;div&amp;gt;Loading...&amp;lt;/div&amp;gt;;
      }
      return &amp;lt;div&amp;gt;User: {props.user.name}&amp;lt;/div&amp;gt;;
    }}
  /&amp;gt;
);

export default App;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;How Relay’s Innovations Were Brought to React Through React Server Components&lt;/p&gt;

&lt;p&gt;Relay introduced several groundbreaking features and methodologies for data handling and fetching in React applications. These features provided developers with a robust framework for managing complex data dependencies and optimizing client-side rendering. &lt;/p&gt;

&lt;p&gt;React Server Components (RSC) have taken some of these innovations and integrated them into a server-rendered paradigm, enhancing the capabilities of React applications. This section emphasizes how the core functionalities of Relay have been adapted and evolved into React Server Components.&lt;/p&gt;

&lt;p&gt;1) &lt;strong&gt;Declarative Data Fetching: From Relay to React Server Components&lt;br&gt;
Relay’s Approach&lt;br&gt;
Relay:&lt;/strong&gt; In Relay, data fetching is declarative. Each component specifies its data requirements using GraphQL fragments, which are then composed into a single query by Relay. This approach ensures that data dependencies are clear and co-located with the component that uses them.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { graphql, QueryRenderer } from 'react-relay';

const UserComponent = () =&amp;gt; (
  &amp;lt;QueryRenderer
    environment={environment}
    query={graphql`
      query UserComponentQuery {
        user(id: "1") {
          name
          email
        }
      }
    `}
    render={({ error, props }) =&amp;gt; {
      if (error) {
        return &amp;lt;div&amp;gt;Error!&amp;lt;/div&amp;gt;;
      }
      if (!props) {
        return &amp;lt;div&amp;gt;Loading...&amp;lt;/div&amp;gt;;
      }
      return (
        &amp;lt;div&amp;gt;
          &amp;lt;h1&amp;gt;{props.user.name}&amp;lt;/h1&amp;gt;
          &amp;lt;p&amp;gt;{props.user.email}&amp;lt;/p&amp;gt;
        &amp;lt;/div&amp;gt;
      );
    }}
  /&amp;gt;
);

export default UserComponent;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;How was it solidified in RSC: R&lt;/strong&gt;eact Server Components also use a declarative approach to data fetching, but with a key difference: data fetching occurs on the server. This allows for direct and efficient access to server-side resources without additional client-side requests.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// UserComponent.server.js
import React from 'react';

const fetchUserData = async (id) =&amp;gt; {
  const response = await fetch(`https://api.example.com/users/${id}`);
  return response.json();
};

const UserComponent = async ({ id }) =&amp;gt; {
  const user = await fetchUserData(id);
  return (
    &amp;lt;div&amp;gt;
      &amp;lt;h1&amp;gt;{user.name}&amp;lt;/h1&amp;gt;
      &amp;lt;p&amp;gt;{user.email}&amp;lt;/p&amp;gt;
    &amp;lt;/div&amp;gt;
  );
};

export default UserComponent;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;2) &lt;strong&gt;Optimized Data Fetching and Minimization&lt;br&gt;
Relay’s Approach&lt;br&gt;
Relay&lt;/strong&gt;: Relay optimizes data fetching by composing multiple component queries into a single network request. This minimizes the number of requests and ensures that only the required data is fetched.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { commitMutation, graphql } from 'react-relay';

function updateUser(environment, userId, newName) {
  const mutation = graphql`
    mutation UpdateUserMutation($input: UpdateUserInput!) {
      updateUser(input: $input) {
        user {
          id
          name
        }
      }
    }
  `;

  const variables = {
    input: {
      id: userId,
      name: newName,
    },
  };

  commitMutation(environment, {
    mutation,
    variables,
    optimisticResponse: {
      updateUser: {
        user: {
          id: userId,
          name: newName,
        },
      },
    },
    onCompleted: (response, errors) =&amp;gt; {
      console.log('Mutation completed');
    },
    onError: (err) =&amp;gt; console.error(err),
  });
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;How was it solidified in RSC:&lt;/strong&gt; React Server Components leverage the server’s ability to directly fetch and render data, eliminating the need for multiple client-side data fetching operations. This approach inherently minimizes network requests and optimizes the data fetching process.&lt;/p&gt;

&lt;p&gt;3) &lt;strong&gt;Component Co-location and Data Dependency Management&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;Relay’s Approach&lt;/strong&gt;&lt;br&gt;
Relay: Data requirements are co-located with the components that use them, making it easier to manage and understand data dependencies.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const UserFragment = graphql`
  fragment UserComponent_user on User {
    name
    email
  }
`;

const UserComponent = ({ user }) =&amp;gt; (
  &amp;lt;div&amp;gt;
    &amp;lt;h1&amp;gt;{user.name}&amp;lt;/h1&amp;gt;
    &amp;lt;p&amp;gt;{user.email}&amp;lt;/p&amp;gt;
  &amp;lt;/div&amp;gt;
);

export default createFragmentContainer(UserComponent, {
  user: UserFragment,
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;How was it solidified in RSC: In React Server Components, data fetching and rendering logic are similarly co-located. This maintains clarity and modularity, allowing developers to understand and manage data dependencies within the component itself.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// UserComponent.server.js
const fetchUserData = async (id) =&amp;gt; {
  const response = await fetch(`https://api.example.com/users/${id}`);
  return response.json();
};

const UserComponent = async ({ id }) =&amp;gt; {
  const user = await fetchUserData(id);
  return (
    &amp;lt;div&amp;gt;
      &amp;lt;h1&amp;gt;{user.name}&amp;lt;/h1&amp;gt;
      &amp;lt;p&amp;gt;{user.email}&amp;lt;/p&amp;gt;
    &amp;lt;/div&amp;gt;
  );
};

export default UserComponent;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;4) &lt;strong&gt;Improved Performance and SEO:&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;Relay’s Approach&lt;/strong&gt;&lt;br&gt;
Relay: Relay improves client-side performance by reducing over-fetching and providing mechanisms for efficient updates. However, because it operates on the client side, initial loading times and SEO can still be challenging.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;How was it solidified in RSC:&lt;/strong&gt; React Server Components significantly enhance performance and SEO by rendering components on the server. The server can send fully-rendered HTML to the client, reducing the amount of JavaScript needed on the client side and providing immediate content for search engines to crawl.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Server-side rendering logic
import { renderToString } from 'react-dom/server';
import App from './App';

const serverRender = (req, res) =&amp;gt; {
  const html = renderToString(&amp;lt;App /&amp;gt;);
  res.send(`&amp;lt;!DOCTYPE html&amp;gt;
&amp;lt;html&amp;gt;
&amp;lt;head&amp;gt;
  &amp;lt;title&amp;gt;React Server Components&amp;lt;/title&amp;gt;
&amp;lt;/head&amp;gt;
    &amp;lt;body&amp;gt;
           &amp;lt;div id="root"&amp;gt;${html}&amp;lt;/div&amp;gt;
           &amp;lt;script src="/bundle.js"&amp;gt;&amp;lt;/script&amp;gt;
    &amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;
`);
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;5) &lt;strong&gt;Hybrid Rendering Model&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;Relay’s Approach&lt;/strong&gt;&lt;br&gt;
Relay: While Relay focuses on client-side data management and rendering, it does not inherently support server-side rendering.&lt;/p&gt;

&lt;p&gt;How was it solidified in RSC: React Server Components introduce a hybrid rendering model, where server-rendered components can seamlessly integrate with client-rendered components. This hybrid approach allows developers to leverage the benefits of both server-side and client-side rendering within the same application.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// App.server.js
import React from 'react';
import HeaderComponent from './HeaderComponent.server';
import FooterComponent from './FooterComponent';
import UserComponent from './UserComponent.server';

const App = () =&amp;gt; (
  &amp;lt;div&amp;gt;
    &amp;lt;HeaderComponent /&amp;gt;
    &amp;lt;UserComponent id="1" /&amp;gt;
    &amp;lt;FooterComponent /&amp;gt;
  &amp;lt;/div&amp;gt;
);

export default App;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;6) &lt;strong&gt;Enhanced Developer Experience&lt;/strong&gt;&lt;br&gt;
Relay’s Approach&lt;br&gt;
Relay: Relay provides tools and conventions for managing GraphQL data, but it requires developers to understand and work with GraphQL schemas, queries, and mutations.&lt;/p&gt;

&lt;p&gt;How was it solidified in RSC: React Server Components simplify the developer experience by allowing direct access to server-side data sources without requiring GraphQL. This reduces the learning curve and allows developers to use familiar REST APIs or other data sources.&lt;/p&gt;

&lt;p&gt;7) Optimistic Updates:&lt;br&gt;
&lt;strong&gt;Relay’s Approach&lt;/strong&gt;&lt;br&gt;
Relay: Relay supports optimistic updates, allowing the UI to be updated immediately based on an expected result while the actual mutation request is processed in the background. This feature improves the user experience by providing instant feedback.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { commitMutation, graphql } from 'react-relay';

function updateUser(environment, userId, newName) {
  const mutation = graphql`
    mutation UpdateUserMutation($input: UpdateUserInput!) {
      updateUser(input: $input) {
        user {
          id
          name
        }
      }
    }
  `;

  const variables = {
    input: {
      id: userId,
      name: newName,
    },
  };

  commitMutation(environment, {
    mutation,
    variables,
    optimisticResponse: {
      updateUser: {
        user: {
          id: userId,
          name: newName,
        },
      },
    },
    onCompleted: (response, errors) =&amp;gt; {
      console.log('Mutation completed');
    },
    onError: (err) =&amp;gt; console.error(err),
  });
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;How was it solidified in RSC:&lt;/strong&gt; React Server Components (RSC) provide a robust framework for handling optimistic updates. By leveraging server-side rendering, RSC can pre-render components with expected data changes, ensuring immediate UI feedback while maintaining consistency and integrity.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
import { use, Suspense } from 'react-server-dom';

function UserComponent({ userId, optimisticData }) {
  const user = use(fetchUser(userId));
  return (
    &amp;lt;div&amp;gt;
      &amp;lt;h1&amp;gt;{optimisticData ? optimisticData.name : user.name}&amp;lt;/h1&amp;gt;
      {optimisticData ? null : &amp;lt;p&amp;gt;Loading...&amp;lt;/p&amp;gt;}
    &amp;lt;/div&amp;gt;
  );
}

async function fetchUser(userId) {
  const response = await fetch(`/api/users/${userId}`);
  return response.json();
}

async function updateUser(userId, newName) {
  // Simulate a delay for updating user
  await new Promise((resolve) =&amp;gt; setTimeout(resolve, 1000));
  return { id: userId, name: newName };
}

// Example usage with optimistic UI
function App({ userId }) {
  const optimisticData = { name: 'Optimistic Name' }; // Mock optimistic data

  return (
    &amp;lt;Suspense fallback={&amp;lt;p&amp;gt;Loading...&amp;lt;/p&amp;gt;}&amp;gt;
      &amp;lt;UserComponent userId={userId} optimisticData={optimisticData} /&amp;gt;
    &amp;lt;/Suspense&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;8) &lt;strong&gt;Subsequent Data Fetching&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;Relay optimizes subsequent data fetching through&lt;/strong&gt;:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Declarative Data Requirements&lt;/strong&gt;: Components declare their data needs, and Relay fetches the necessary data.&lt;br&gt;
Query Batching: Relay batches multiple GraphQL queries into a single request, reducing network overhead.&lt;br&gt;
Caching: Relay caches query results, minimizing redundant network requests.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Automatic Refetching&lt;/strong&gt;: Relay refetches data when variables change, keeping the UI up-to-date.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Client-Side Data Fetching with Relay
import { useQueryLoader, usePreloadedQuery } from 'react-relay/hooks';
import { MyQuery } from './MyQuery';

function MyComponent() {
  const [queryReference, loadQuery] = useQueryLoader(MyQuery);

  useEffect(() =&amp;gt; {
    loadQuery({ id: 'some-id' });
  }, [loadQuery]);

  if (!queryReference) {
    return &amp;lt;div&amp;gt;Loading...&amp;lt;/div&amp;gt;;
  }

  return &amp;lt;DisplayData queryReference={queryReference} /&amp;gt;;
}

function DisplayData({ queryReference }) {
  const data = usePreloadedQuery(MyQuery, queryReference);
  return &amp;lt;div&amp;gt;{data.user.name}&amp;lt;/div&amp;gt;;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;How was it solidified in RSC: React Server Components (RSC) take the concept of subsequent data fetching further by performing data fetching on the server. This approach offloads the responsibility of data fetching from the client to the server, enhancing performance and reducing client-side complexity.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { use } from 'react-server-dom';

function UserComponent({ userId }) {
  const user = use(fetchUser(userId));
  return &amp;lt;div&amp;gt;{user.name}&amp;lt;/div&amp;gt;;
}

async function fetchUser(userId) {
  const response = await fetch(`/api/users/${userId}`);
  return response.json();
}

export default UserComponent;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Conclusion:&lt;/strong&gt;&lt;br&gt;
Relay introduced several advanced features that have profoundly influenced the development of data-driven React applications. These features, including declarative data fetching, optimized data fetching and minimization, component co-location, and data dependency management, have set a high standard for managing complex data needs in React.&lt;/p&gt;

&lt;p&gt;React Server Components have taken these foundational concepts and adapted them to enhance server-side rendering capabilities. By leveraging server-side execution, React Server Components offer significant improvements in performance, SEO, and developer experience. The transition from Relay’s client-side optimizations to RSC’s server-side capabilities represents a natural evolution, providing developers with powerful tools to build more efficient and performant applications.&lt;/p&gt;

&lt;p&gt;As React continues to evolve, the integration of these advanced features into the core framework through React Server Components demonstrates React’s commitment to addressing the challenges of modern web development and providing inn&lt;/p&gt;

</description>
      <category>react</category>
      <category>reactservercomponents</category>
      <category>relay</category>
    </item>
  </channel>
</rss>
