<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Elene Shengelia on Medium]]></title>
        <description><![CDATA[Stories by Elene Shengelia on Medium]]></description>
        <link>https://medium.com/@EleneSh?source=rss-24db65291ea3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*bqCGyCU4J0Mbw_bxEGOF0Q.jpeg</url>
            <title>Stories by Elene Shengelia on Medium</title>
            <link>https://medium.com/@EleneSh?source=rss-24db65291ea3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 21:28:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@EleneSh/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Prompt Engineering as a Debugging Process]]></title>
            <link>https://medium.com/@EleneSh/prompt-engineering-as-a-debugging-process-dc5f98ce682f?source=rss-24db65291ea3------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc5f98ce682f</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[gemini]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[prompt-engineering]]></category>
            <dc:creator><![CDATA[Elene Shengelia]]></dc:creator>
            <pubDate>Wed, 25 Feb 2026 15:03:37 GMT</pubDate>
            <atom:updated>2026-02-25T15:06:35.549Z</atom:updated>
            <content:encoded><![CDATA[<p>If you search “prompt engineering”, you’ll find a million posts telling you <em>patterns that work</em>. But instead of trying to memorize prompt patterns, I did something more boring. I kept a timeline of prompt changes in my project: what I changed, what broke, what improved, and what that probably says about how the model “thinks”.</p><p>This article is basically my prompt debug log, cleaned up into something readable.</p><p>Also:<strong> this is personal experience</strong>. I might be wrong. I’m writing this because I want to re-check my thinking and spot problems I still don’t see.</p><h3>Before anything: a short note on terminology</h3><p>A prompt — is just the input we give the model so it can produce the next output.</p><p><strong>A Large Language Model </strong>— is a next-word prediction machine. You give it some text, and it predicts what text should come next. A simple mental model for text models (LLMs) is this: It predicts the next chunk of text, then the next, then the next… until it stops. It’s more like extremely advanced autocomplete.<em> </em><strong><em>That’s why wording matters</em></strong><em> — it changes what pattern the model continues. The better the context, the better its predictions.</em></p><h3>What about temperature, top-K, and all those settings?</h3><p>At <strong>temperature</strong> 0, the model always picks the most likely next word. Very predictable. Very safe. Sometimes very boring or flat. As you increase temperature (say 0.4, 0.7, 1.0), the model starts considering less likely options. You get more variety and creativity but also more randomness and occasional weirdness.</p><p><strong>Top-K</strong> limits how many options the model considers at each step. Top-K of 40 means it only looks at the 40 most likely next words before choosing. Lower numbers mean more focus.Higher numbers mean more diversity.</p><h3>The actual problem my prompts were trying to solve</h3><p>One of my project’s goal sounded simple in one sentence: Convert a 2D floor plan into a photorealistic 3D interior view, at eye level, without breaking the layout.</p><p>I am using image generation models (primarily Gemini) that take images as input and produce images as output.</p><p>The core challenge was getting the AI to look at a flat 2D floor plan and produce a realistic photo of what that room would look like from the inside at eye level with correct walls, windows, doors, materials, and lighting.</p><p>Here’s what actually happened, phase by phase.</p><h3>Phase 1: The polite prompt (and why it failed)</h3><p><em>Generate a photorealistic 3D interior photograph from this floor plan. Camera at human eye level. Floor at bottom, ceiling at top.</em></p><p>The result — Top-down and birds eye views. Everything except what a person standing inside the room would actually see. What I learned: The model defaulted to top-down views because <em>“floor plan → top-down”</em> is a very strong mental shortcut.</p><h3>Phase 2: Over-correcting with “DO NOT”</h3><p>So I went into full angry mode: What you MUST NOT create: Top-down view; Bird’s-eye view; Isometric -Any view showing the entire floor layout from above.</p><p>It helped but it also introduced a strange side effect. The more “DON’Ts” I added, the more unstable the outputs felt. Lesson: <strong>Negative constraints help, but too many become noise</strong>. They also don’t tell the model what to do <em>instead</em>.</p><h3>Phase 3: The shift to tell it what TO do, very precisely</h3><p>Instead of saying <em>“don’t make a top-down view”</em>, I tried this: “Horizon line centered vertically at approximately 50% from the top. All vertical architectural lines remain perfectly parallel to image edges. Zero-Tilt: all vertical edges must be 90° to the horizon.” This worked noticeably better. What I learned: <strong>Positive, specific, measurable instructions beat negative.</strong></p><h3>Phase 4: The role change mattered more than expected</h3><p>I changed my system instruction from: “Act as an Architectural Visualizer” to: “Act as a Professional Interior Photographer”. The outputs shifted toward eye-level perspectives almost immediately.</p><p>My theory is that the model’s training data associates <em>“architect”</em> with blueprints, plans, and top-down diagrams, while <em>“photographer”</em> is associated with eye-level shots, composition, and real-world perspectives. <em>I’m not 100% sure this explanation is correct but the results were consistent enough that I kept it.</em></p><h3>Phase 5: Language mattered more than I expected</h3><p>Calling structural elements “immutable anchors” worked better than saying <em>“don’t move the walls”</em>. The model seemed to respond much better to <strong>domain-specific terminology</strong> — words that are strongly tied to concrete concepts in its training data. What I learned: Use the vocabulary of the domain you want the output to match. If you want architectural accuracy, use architectural terms. If you want photographic quality, use photography terms.</p><h3>Phase 6: Multi-pass beats single-pass, always</h3><p>Trying to do everything in one prompt never worked reliably.</p><p>So I split the process:</p><p><strong>Pass 1</strong>: Generate a <em>render</em> — a plain white architectural model with correct geometry, shadows, and perspective. No textures. No furniture. No colors. Low temperature (0.2) for consistency.</p><p><strong>Pass 2</strong>: Take that render and add materials, furniture, and lighting. Use reference images for style. Higher temperature (0.4) for creative freedom.</p><p>This was far more stable than any single-pass prompt.</p><h3>What actually helped</h3><p>What actually helped wasn’t clever prompts. It was documenting what worked, what didn’t, and asking why.</p><p>This article comes from a real project I built, but the lessons apply even if you’re just typing questions into a chat window. No code. No settings. Just curiosity and patience.</p><p>Document everything as you go. Not in a polished way. <strong>Just messy notes: “Tried X, got Y, expected Z.” That’s it.</strong></p><p>After a few weeks, go back and read your notes. Patterns will jump out. You’ll see your recurring mistakes. Experiment, document and analyze.</p><h3>Why this works better than memorizing tips</h3><p>Prompt engineering is deeply <strong>context-dependent</strong>. What works for interior rendering doesn’t directly work for code generation or essay writing. The patterns I found are specific to my use case, my model, and my inputs. <strong>Your patterns will be different</strong>.</p><p><em>I might be wrong about some explanations in this article. I’m explaining why I think certain things worked, based on my understanding of how these models work. The internal mechanics may be different.</em></p><p><em>I’m not an ML researcher.I’m a developer who needed to get something working. </em>And this is what actually helped.</p><p>I’m currently experimenting with Gemini voice models for my next project. I’m approaching it the same way. If I learn something useful, I’ll probably update this article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc5f98ce682f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How React Server Components Work — Exploring Without a Framework]]></title>
            <link>https://medium.com/@EleneSh/why-react-needs-frameworks-but-not-always-7c6161b9628f?source=rss-24db65291ea3------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c6161b9628f</guid>
            <category><![CDATA[webpack]]></category>
            <category><![CDATA[react-server-component]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[react-19]]></category>
            <dc:creator><![CDATA[Elene Shengelia]]></dc:creator>
            <pubDate>Sun, 10 Nov 2024 17:55:59 GMT</pubDate>
            <atom:updated>2024-11-13T18:37:08.852Z</atom:updated>
            <content:encoded><![CDATA[<h3>How React Server Components Work — Exploring Without a Framework</h3><p>In this article, I’ll try to explain some important concepts in React, including SSR (server side Rendering) and RSC (React server components). I’ll also touch on when using frameworks is necessary, when it’s not, and why React requires some additional setup for these features when not using a framework.</p><p>Before exploring server side rendering (SSR) and React server components (RSC), it’s important to understand how React applications are traditionally built and served to browsers.</p><h4>Understanding How Browsers Process React Code</h4><p>When developing React applications, we write modular code by splitting our application into components and importing them into one another. This might include an App component that imports Header and Footer components, creating a clean and organized codebase. However, browsers don’t natively understand these module imports the way developers do when writing code. Browsers only understand plain JavaScript, typically expecting a single file (or a few separate files) with global variables or functions.</p><h4>The Role of Bundlers</h4><p>This is where bundlers like Webpack come into play. Webpack is a critical tool that transforms your React application’s code into a browser-optimized format. It performs several essential functions in React: JSX and ES6+ transpilation (since browsers don’t directly support JSX, Webpack uses Babel to convert React components into standard JavaScript), dependency management (bundling all third-party libraries like react, redux, etc. into a single file or multiple optimized chunks), and bundle generation (creating one or more JavaScript bundles that browsers can efficiently download and execute).</p><h4>Client side rendering</h4><p>In client side rendering model entire React application runs in the browser. When a user visits website, the server sends a minimal HTML file along with a <strong>bundled </strong>JavaScript file containing entire application. The browser downloads this bundle, executes it, and React takes over by constructing the virtual DOM, and making the application interactive through a process called hydration.</p><p>This approach has some problems that directly led to the development of SSR and RSC. The initial page load can be slow since users must download and execute the entire JavaScript bundle before seeing any content. Additionally, search engines might have difficulty indexing content since the initial HTML is nearly empty before JavaScript runs.</p><p>Understanding these fundamentals about bundling and client-side rendering helps us better understand how SSR and RSC works.</p><h4>Understanding SSR</h4><p>SSR is a method where HTML is rendered on the server and then sent to the client, which helps the client display content faster and avoids showing a blank screen during the loading phase. However, even with SSR, the client still needs to download the entire JavaScript bundle to hydrate the app and make it interactive. This means that while the user gets to see the HTML right away, they still have to wait for JavaScript to be downloaded and executed for the app to be fully functional.</p><p>In traditional SSR, React renders the full HTML on the server using functions like renderToString or renderToNodeStream, and then sends that to the client. The issue with this approach is that the server generates the entire HTML and sends it to the client all at once. The client has to wait for the server to finish rendering before it can display anything, which causes delays.</p><p>But in React 18 <a href="https://react.dev/reference/react-dom/server/renderToPipeableStream">renderToPipeableStream </a>API were introduced for server side rendering, which improves how React handles data sent to the client. This new function is designed to stream content in a way that’s faster and more efficient compared to the older renderToNodeStream API.</p><p>With renderToPipeableStream, the server can start sending the HTML content as soon as it&#39;s available, rather than waiting. This is because renderToPipeableStream creates a &quot;pipeable&quot; stream, which means the server can continuously send small chunks of the HTML to the client, rather than waiting to send the entire page at once.</p><p>To understand how this works, let’s also explain what a suspense boundary is in React. Suspense is a feature that lets components “wait” while data loads, showing placeholder content for specific sections. When paired with renderToPipeableStream, the server can immediately send fully loaded content to users while other parts are still loading - making websites feel faster and more responsive.</p><p>Here’s how they work together — when renderToPipeableStream starts, it immediately sends the initial HTML, including any non-suspended content. This means users see the basic page structure right away.</p><pre>function App() {<br>    return (<br>        &lt;div&gt;<br>            &lt;Header /&gt; {/* Sends immediately */}<br>            &lt;Suspense fallback={&lt;LoadingSpinner /&gt;}&gt;<br>                &lt;ProductList /&gt; {/* Waits for data */}<br>            &lt;/Suspense&gt;<br>            &lt;Footer /&gt; {/* Sends immediately */}<br>        &lt;/div&gt;<br>    );<br>}</pre><h4>RSC — <strong>React Server Components</strong></h4><p>But The biggest change with React 18 and 19 is the introduction of <strong>React server components (RSC)</strong>. RSC is a new programming model and architecture concept introduced by React. With RSC, you can render parts of your React application on the server and the server will send a serialized representation<strong> </strong>of them to the client.</p><p>The key benefit of this is that the client does not need to download a full JavaScript bundle, server components are rendered entirely on the server, and their data is streamed directly to the client, the client only needs to download a smaller bundle for client components. This reduced bundle size means faster downloads, faster page loads, and better performance overall. Additionally, React server components allow developers to include server specific logic like authentication and authorization directly in their React components. By handling these tasks — server side sensitive logic stays on the server so you can build React applications that are more performant and secure.</p><h4>Setting Up React Server Components</h4><p>RSC, however, is more than just a feature — it’s a new architecture for building applications, but It doesn’t come fully set up out of the box and requires specific tools and structure to work effectively. RSC needs <strong>bundling </strong>and routing support to function properly. For example, a bundler like Webpack is essential for separating server and client components. Proper bundling ensures that the client downloads only the parts it needs for interactive components, rather than the entire bundle. To achieve this separation, we use the &quot;use client&quot; directive. When configured correctly, adding &quot;use client&quot; at the top of a component tells Webpack to generate a separate bundle specifically for client side components. This means server specific tasks stay on the server, while client-specific code is bundled independently and downloaded by the client as needed.</p><p>Frameworks like Next.js have built-in support for these features — bundling, routing, and RSC configuration — so developers can use RSC model without needing to set up everything from scratch. However, for educational purposes, we can create a simpler version of this setup with React. We’ll start by creating a custom bundler configuration, and setting up a basic Express server. We’ll include some client and server components to demonstrate the RSC model and how directives like use client are applied. You can clone my <a href="https://github.com/elenesheng/rsc">repository</a> to follow along more easily.</p><p><em>It’s a simple setup to demonstrate how RSC works without a framework. It can be useful for learning purposes but isn’t a complex example.</em></p><p><strong>//build.js</strong></p><pre>const path = require(&quot;path&quot;);<br>const webpack = require(&quot;webpack&quot;);<br>const ReactServerWebpackPlugin = require(&quot;react-server-dom-webpack/plugin&quot;);<br><br>webpack(<br>    {<br>        mode: &quot;development&quot;,<br>        entry: [path.resolve(__dirname, &quot;../src/index.js&quot;)],<br>        output: {<br>            path: path.resolve(__dirname, &quot;../public&quot;),<br>            filename: &quot;main.js&quot;,<br>        },<br>        module: {<br>            rules: [<br>                {<br>                    test: /\.js$/,<br>                    use: &quot;babel-loader&quot;,<br>                    exclude: /node_modules/,<br>                },<br>            ],<br>        },<br>        plugins: [new ReactServerWebpackPlugin({ isServer: false })],<br>    },<br>    (error, stats) =&gt; {<br>        if (error) {<br>            console.error(error);<br>        }<br>    }<br>);</pre><p>This configuration handles React server components by splitting client and server code through the ReactServerWebpackPlugin with { isServer: false } for client-side bundling.</p><p>Webpack here Uses Babel (through babel-loader) to transform JSX and modern JavaScript into browser compatible code and generates the final bundle in public/main.js</p><p>When Webpack runs, it generates key outputs: the client bundle and react-client-manifest.json.</p><p>The client.main.js bundle contains only the code necessary for client-side components, optimizing the initial load time and reducing the amount of data the client needs to download.</p><p>The react-client-manifest.json file, generated by Webpack, is a important in the RSC model, it stores information about the client side components. Server rendered components are sent to the client as serialized data, this serialized output not only contains the server rendered components but also includes placeholders or references to any client components that need to be hydrated or interact on the client side.</p><p>Here’s where the manifest comes in. The react-client-manifest.json helps server instruct the client to only download the specific client-side bundle it needs. This selective downloading reduces load time and improves performance.</p><p>Later, we’ll explore how server.js utilizes this manifest file to reference client components in the RSC payload.</p><p><strong>//server.js</strong></p><pre>const register = require(&quot;react-server-dom-webpack/node-register&quot;);<br>register();<br>const path = require(&quot;path&quot;);<br>const { readFileSync } = require(&quot;fs&quot;);<br>const babelRegister = require(&quot;@babel/register&quot;);<br><br>babelRegister({<br>    ignore: [/[\\\/](build|server|node_modules)[\\\/]/],<br>    presets: [[&quot;@babel/preset-react&quot;, { runtime: &quot;automatic&quot; }]],<br>    plugins: [&quot;@babel/transform-modules-commonjs&quot;],<br>});<br><br>const { renderToPipeableStream } = require(&quot;react-server-dom-webpack/server&quot;);<br><br>const express = require(&quot;express&quot;);<br><br>const React = require(&quot;react&quot;);<br>const ReactApp = require(&quot;../src/components/App&quot;).default;<br><br>const app = express();<br><br>app.get(&quot;/&quot;, (req, res) =&gt; {<br>    const html = readFileSync(<br>        path.resolve(__dirname, &quot;../public/index.html&quot;),<br>        &quot;utf8&quot;<br>    );<br>    res.send(html);<br>});<br><br>app.get(&quot;/react&quot;, (req, res) =&gt; {<br>    const manifest = readFileSync(<br>        path.resolve(__dirname, &quot;../public/react-client-manifest.json&quot;),<br>        &quot;utf8&quot;<br>    );<br>    const moduleMap = JSON.parse(manifest);<br>    const { pipe } = renderToPipeableStream(<br>        React.createElement(ReactApp),<br>        moduleMap<br>    );<br>    pipe(res);<br>});<br><br>app.get(&quot;/getmessage&quot;, (req, res) =&gt; {<br>    setTimeout(() =&gt; {<br>        res.json({ message: &quot;This message is from the server-side API.&quot; });<br>    }, 2000);<br>});<br><br>app.use(express.static(path.resolve(__dirname, &quot;../public&quot;)));<br>const port = process.env.PORT || 3000;<br>app.listen(port, () =&gt; console.log(`listening on port ${port}`));</pre><p>The module react-server-dom-webpack/node-register is used to set up the server side environment for rendering React components. When the /react endpoint is accessed, it generates a special RSC payload. This payload is a special format that includes serialized server component render results and references to client components.</p><p>The renderToPipeableStream function is used here to create the RSC payload. This function takes two main inputs — the first is React.createElement(ReactApp), which represents the main React component that will be rendered on the server. The second is the moduleMap. moduleMap is our client manifest file converted into a JavaScript object format via JSON.parse()— which helps the server know which client components to reference in the RSC payload. The line pipe(res) streams the RSC payload directly to the client, allowing the client to start rendering parts of the page as soon as data arrives, rather than waiting for the entire payload to load before anything appears on the page.</p><p>also /getmessage endpoint sends a JSON response with a message after a delay of two seconds. The delay simulates a realistic wait time for fetching data from a server. Later, we’ll use this endpoint in our server component</p><p><strong>//ServerComponent.js</strong></p><pre>export async function ServerComponent() {<br>    const response = await fetch(&#39;http://localhost:3000/getmessage&#39;);<br>    const { message } = await response.json();<br><br>    return (<br>        &lt;div&gt;<br>            &lt;h2&gt;Server Component&lt;/h2&gt;<br>            &lt;p&gt;{message}&lt;/p&gt;<br>        &lt;/div&gt;<br>    );<br>}</pre><p>ServerComponent fetches data directly on the server, from our /getMessage endpoint.</p><p><strong>//ClienTComponent.js</strong></p><pre>&quot;use client&quot;;<br><br>export const ClientComponent = () =&gt; {<br>    return (<br>        &lt;div&gt;<br>            &lt;h2&gt;Client Component&lt;/h2&gt;<br>            &lt;p&gt;This is a client-side component.&lt;/p&gt;<br>        &lt;/div&gt;<br>    );<br>};</pre><p>In this example, ClientComponent is marked with <a href="https://react.dev/reference/rsc/use-client">&quot;use client&quot; </a>at the top of the file. This directive tells React and the bundler that this component, and any components or functions it imports, should be rendered/hydrated on the client side.</p><p><strong>//App.js</strong></p><pre>import { Suspense } from &quot;react&quot;;<br>import { ServerComponent } from &quot;./ServerComponent&quot;;<br>import { ClientComponent } from &quot;./ClientComponent&quot;;<br><br>export default async function App() {<br>    return &lt;div className=&quot;main&quot;&gt;<br>        &lt;Suspense fallback={&lt;div&gt;loading...&lt;/div&gt;}&gt;<br>            &lt;ServerComponent /&gt;<br>        &lt;/Suspense&gt;<br>        &lt;ClientComponent /&gt;<br>    &lt;/div&gt;;<br>}</pre><p>In our main App, we wrap the ServerComponent with the Suspense component. This setup is particularly useful because it lets the data from the server stream to the client gradually using renderToPipeableStream. As a result, parts of the page can load and display as soon as they’re ready, without waiting for everything to load at once.</p><p>For example, the ServerComponent will render after a 2-second delay (simulated in server.js), while the ClientComponent renders immediately, without delay. If there were any other components available right away, they would also be displayed with the ClientComponent instantly. The ServerComponent will appear after the 2 second delay, demonstrating how React can load server and client components independently.</p><p><em>Feel free to explore the rest of the code in my repository and experiment with it.</em></p><p>When you use a framework like Next.js, it simplifies many aspects we talked about by handling bundling and routing automatically. This means you don’t need to worry about setting up a custom Express server or manually configuring a bundler. Next.js takes care of these tasks, it uses its built-in routing system to handle requests and map them to the right server components, and it also takes care of bundling.</p><p>But this simplicity comes with a bit of limitations in terms of flexibility. While Next.js handles most of the configurations for you, you might feel restricted in some areas if you want to completely control things like if you want to configure your bundlers you should do it through Next.js config or if you want to change routing behavior.</p><p>Next.js allows you to quickly set up and running without needing to configure everything from scratch. However, if you need full control over the bundling process or routing logic, you might hit some limitations.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c6161b9628f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding React Compiler]]></title>
            <link>https://medium.com/@EleneSh/understanding-react-compiler-78a51b1815f2?source=rss-24db65291ea3------2</link>
            <guid isPermaLink="false">https://medium.com/p/78a51b1815f2</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[memoization]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-compiler]]></category>
            <category><![CDATA[performance-optimization]]></category>
            <dc:creator><![CDATA[Elene Shengelia]]></dc:creator>
            <pubDate>Mon, 21 Oct 2024 19:44:43 GMT</pubDate>
            <atom:updated>2024-10-21T19:59:14.331Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s01pz6gK_2riql2CyyKcqg.jpeg" /><figcaption>AI-generated image</figcaption></figure><p>Just a few days ago, I published an article about memoization techniques in React, which I am currently using in my projects. I believe this knowledge is still relevant and will continue to be valuable, even after the React compiler becomes more widely used. The reason is that understanding how memoization works, is still important, even though the React compiler automates many of these tasks for us.</p><p>Before continuing, if you haven’t read my <a href="https://medium.com/@EleneSh/react-optimization-strategies-focus-on-memoization-bc50f91463b6">previous article</a> about React memoization techniques, I recommend checking it out. It will help you understand how React optimizations work, which is helpful when learning about the React compiler.</p><h3>What is a Compiler?</h3><p>Generally a compiler is a tool that converts the code you write into a form that the computer can understand and execute.</p><p>JavaScript compilers like Babel are used to convert modern JavaScript into older versions, making it compatible with environments that don’t support the latest JavaScript features. While traditional compilers work at a low level (closer to the computer’s language), transforming human-readable code into machine instructions, JavaScript compilers like Babel operate at a higher level<strong> </strong>(code that’s easier for humans to understand<strong>)</strong>. They transform one form of JavaScript into another version that is easier for different environments to understand while remaining human-readable.</p><h4>React Compiler</h4><p>The React Compiler is a tool that optimizes your JavaScript code, it is currently a beta version and can be used through a Babel plugin. While Babel is primarily used to convert JavaScript syntax, the React Compiler automatically optimizes your React code. The core of the React Compiler is separate from Babel, but it integrates with the build process using Babel.</p><p>We know that objects and functions are recreated on every render, and reference changes can cause performance issues. This leads to the re-rendering of child components even if the content of the object hasn’t changed, or if the properties that the child component is using haven’t changed. This is a key problem that the React Compiler solves. React Compiler is a “build-time-only” tool, during the build process, it analyzes your components to understand which props and state actually affect the rendered output. Based on this analysis, it generates optimized code that only checks for changes in these specific values.</p><p>For example:</p><pre>function UserProfile({ user }) {<br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;{user.name}&lt;/h1&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>React Compiler ensures that React only cares about changes to the name, not other details like the user’s age that doesn’t show up on screen. By doing this, it reduces unnecessary re-renders and helps keep your app running smoothly.</p><p>If you’ve read my previous article on React memoization, you know that applying these techniques wisely can make your app run more smoothly. However, small mistakes, over-optimization, or not using these techniques at all can lead to worse performance. With the React compiler, you don;t need to optimize your code with useCallback, useMemo or React.memo React automatically handles these optimizations for you, it looks at and improves your code when you build your app. This helps React reduce the amount of checking it needs to do when the app is running. As a result, instead of doing a lot of checks, React can quickly focus on what really needs to be updated.</p><p>The great thing is that, as a developer, you don’t have to change how you write your code. You can write your code as usual, and the React Compiler handles the optimizations for you, including memoization. This makes your app faster during rendering without requiring any extra effort on your part.</p><p>Even though the React compiler is a powerful tool that will make our development process smoother by handling optimizations automatically, it’s still important to understand how memoization works. Knowing these techniques gives you a better idea of how perfomance optimzation works.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=78a51b1815f2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Optimization Strategies - Focus on Memoization]]></title>
            <link>https://medium.com/@EleneSh/react-optimization-strategies-focus-on-memoization-bc50f91463b6?source=rss-24db65291ea3------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc50f91463b6</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[website-perfomance]]></category>
            <category><![CDATA[react-hook-usememo]]></category>
            <category><![CDATA[usecallback-hook]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Elene Shengelia]]></dc:creator>
            <pubDate>Fri, 18 Oct 2024 19:29:05 GMT</pubDate>
            <atom:updated>2024-10-21T19:47:26.140Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qgVHMMzVBAtwyt-nQpBT9Q.jpeg" /><figcaption>Image sourced from Google</figcaption></figure><p>My main reason for writing this article is to review performance optimization techniques in React, focusing on memoization. I often find myself confused when writing React code. There are so many options — you can write simple code with many different variations, and none of them might be technically incorrect, but many can be bad for performance.</p><p>Choosing the correct strategy is a confusing subject. Some developers try to over-optimize everything, while others don’t optimize at all.</p><p>I’d love to welcome feedback and hear others opinions, as it’s such an interesting topic to discuss, I believe sharing our approaches can help us all become better developers.</p><h3>Understanding Memoization</h3><p>Let’s start with an explanation of <strong>memoization —</strong> it’s a technique for storing the result of a function, allowing you to avoid recalculating the same thing twice. If the input is the same, previously memoized (stored) results can be accessed. It’s similar to remembering information for future use — if you encounter the same situation again and need that information, instead of figuring it out again, you already have it in your mind (saves us time).</p><p>When discussing memoization, it’s important to briefly revisit closures, as these two concepts are closely related.</p><p><strong>Closure </strong>occurs when a function remembers and maintains access to variables from its surrounding scope, even after the outer function has finished executing. Memoization often leverages closures to store the cached results of a function. Let’s use an example to demonstrate both — memoization and closures in JavaScript:</p><pre>function memoizedSquare() {<br>    let cache = {};<br><br>    return function(n) {<br>        if (n in cache) {<br>            console.log(&#39;Fetching from cache&#39;);<br>            return cache[n];<br>        } else {<br>            console.log(&#39;Calculating result&#39;);<br>            let result = n * n;<br>            cache[n] = result;<br>            return result;<br>        }<br>    };<br>}<br><br>const square = memoizedSquare();<br>console.log(square(4));  // Calculates<br>console.log(square(4));  // Uses cache<br>console.log(square(5));  // Calculates</pre><p>This code creates a function that remembers the results of squaring numbers. When you ask it to square a number, it first checks if it has done this calculation before. If it has, it quickly gives you the stored answer without redoing the math. If it hasn’t seen this number before, it does the calculation, stores the result for future use, and then gives you the answer.</p><p>This approach, called memoization, makes repeated calculations much faster by avoiding unnecessary work.</p><p><em>The inner function returned by </em><em>memoizedSquare forms a closure, which means it retains access to the </em><em>cache object even after </em><em>memoizedSquare has finished executing. This allows the </em><em>cache to persist between function calls, enabling the memoization process to work by remembering previously calculated results.</em></p><h3>Exploring Memoization Techniques in React</h3><p>As we’ve mentioned, developers have different approaches to writing even small components in React. While I love React for its simplicity, I also find it’s challenging because determining the “best” approach can be subjective — terms like “correct” and “incorrect” often don’t apply. This is even more difficult for freelance developers since they usually don’t have a team, other developers, or clear guidelines to follow.</p><p>There are various opinions on when to use hooks like useCallback or useMemo. Some developers might avoid these optimizations altogether, while others may overuse them.</p><p>Let’s start by revisiting these concepts.</p><blockquote><a href="https://react.dev/reference/react/useMemo"><strong>useMemo</strong></a><strong> — </strong>According to React docs, “useMemo is a React Hook that lets you cache the result of a calculation between re-renders.”</blockquote><pre>const cachedValue = useMemo(calculateValue, dependencies)</pre><p>You can read more about useMemo in the React documentation, but in short you provide useMemo with a function that performs calculation (result from this calculation will be cached) and an array of dependencies. The cached result will only be updated when one of the dependencies changes.</p><blockquote><a href="https://react.dev/reference/react/useCallback"><strong>useCallback</strong></a><strong> —</strong> “useCallback is a React Hook that lets you cache a function definition between re-renders.”</blockquote><pre>const cachedFn = useCallback(fn, dependencies)</pre><p>Here, instead of caching a function’s return value (result), we’re caching the function definition itself. This is useful because functions are recreated on every render unless memoized.</p><blockquote><a href="https://react.dev/reference/react/memo"><strong>React.memo</strong></a><strong> —</strong> “memo lets you skip re-rendering a component when its props are unchanged.”</blockquote><pre>const MemoizedComponent = memo(SomeComponent, arePropsEqual?)</pre><p>React.memo is a <a href="https://medium.com/stackademic/how-functional-programming-benefits-react-developers-52824a3a4f44">Higher Order Component (HOC)</a>, that helps improve performance by preventing a component from re-rendering unless its props change. When you wrap a component in React.memo, it will only update if the props it receives has changed. This is especially helpful for child components to avoid unnecessary re-renders.</p><p>We will talk about each one in detail later.</p><h4>useMemo Hook</h4><p>Using <strong>useMemo </strong>can be beneficial, but it’s important to understand when to use it and when it may not be necessary. If a calculation is lightweight or inexpensive, there’s often no need to use useMemo. In fact, using it can slow down the initial render because React needs to perform extra operations to cache the result. Additionally, useMemo can also slow down re-rendering because React must check whether the dependencies have changed.</p><p>useMemo is most useful for expensive calculations or when rendering output itself is costly. However, over-optimizing by using useMemo can negatively impact performance due to the extra checks that React has to perform. So if a calculation isn’t expensive, it might be better to skip useMemo.</p><p>Typically, rendering operations tend to be more expensive, so memoizing the rendered output might make more sense, let’s see an example:</p><pre>const ProductsList = ({ products }) =&gt; {<br>    const [dummyState, setDummyState] = useState(0); <br><br>    const content = useMemo(() =&gt; {<br>        return products.map((product) =&gt; (<br>            &lt;ProductItem product={product} key={product.id} /&gt;<br>        ));<br>    }, [products]); // Recalculate when products change<br><br>    const handleDummyChange = () =&gt; {<br>        setDummyState(dummyState + 1); // Update dummy state to trigger re-render<br>    };<br><br>    return (<br>        &lt;div&gt;<br>            &lt;h2&gt;Product List&lt;/h2&gt;<br>            &lt;button onClick={handleDummyChange}&gt;Update Dummy State&lt;/button&gt;<br>            &lt;p&gt;Dummy State: {dummyState}&lt;/p&gt;<br>            &lt;div&gt;{content}&lt;/div&gt;<br>        &lt;/div&gt;<br>    );<br>};</pre><p>Using useMemo here prevents unnecessary recalculations of the product list. This makes the rendering process faster when the dummyState or parent component changes and products are the same. While useMemo saves the effort of recreating the array of React elements, the child components will still re-render unless further optimized. To fully prevent unnecessary re-renders, you would need to wrap ProductItem in React.memo and ensure its props are stable. This combination of techniques can significantly improve performance for large lists or complex item components.</p><p><em>It’s also important to use </em><em>useMemo effectively with React context, which we will discuss later.</em></p><h4>useCallback and React.memo</h4><p>When a component re-renders in React, any functions defined inside it are recreated, which means their reference changes with every render. However, useCallback helps us to cache a function and use the same reference. That’s why we often face the common misconception that using useCallback for a function we pass to a child will stop that child from re-rendering. However, that&#39;s not true! Even though useCallback keeps the function reference the same, the child will still re-render if the parent re-renders.</p><p>To prevent the child component from re-rendering unnecessarily, you need to combine useCallback with<strong> </strong>React.memo<strong>.</strong></p><ul><li><strong>useCallback</strong> ensures that the function reference passed to the child component doesn’t change unless its dependencies change.</li><li><strong>React.memo</strong> tells React to only re-render the child component if its props actually change.</li></ul><p>So to sum it up — if a function is cached using useCallback, it will maintain the same reference, allowing React.memo to effectively prevent the child component from re-rendering, because the prop remains the same due to it being cached with useCallback</p><p>Let’s look at an examples. First write simple parent/child component without wrapping child in React.memo:</p><pre>const ParentComponent = () =&gt; {<br>    const [count, setCount] = useState(0);<br><br>    const handleClick = useCallback(() =&gt; {<br>        console.log(&#39;Button clicked&#39;);<br>    }, []);<br><br>    return (<br>        &lt;div&gt;<br>            &lt;h1&gt;Parent Component&lt;/h1&gt;<br>            &lt;p&gt;Count: {count}&lt;/p&gt;<br>            &lt;button onClick={() =&gt; setCount(count + 1)}&gt;Increment&lt;/button&gt;<br>            &lt;ChildComponent onClick={handleClick} /&gt;<br>        &lt;/div&gt;<br>    );<br>};<br><br>export default ParentComponent;<br><br>const ChildComponent = ({ onClick }) =&gt; {<br>    console.log(&#39;Child component rendered&#39;);<br>    return &lt;button onClick={onClick}&gt;Click me&lt;/button&gt;;<br>};</pre><p>In this example, even though we’ve wrapped the handleClick function with useCallback, the ChildComponent will still re-render every time the ParentComponent re-renders (for example when the count state changes).</p><p>The only way to avoid that is to wrap the ChildComponent with React.memo:</p><pre>const ParentComponent = () =&gt; {<br>    const [count, setCount] = useState(0);<br><br>    const handleClick = useCallback(() =&gt; {<br>        console.log(&#39;Button clicked&#39;);<br>    }, []);<br><br>    return (<br>        &lt;div&gt;<br>            &lt;h1&gt;Parent Component&lt;/h1&gt;<br>            &lt;p&gt;Count: {count}&lt;/p&gt;<br>            &lt;button onClick={() =&gt; setCount(count + 1)}&gt;Increment&lt;/button&gt;<br>            &lt;ChildComponent onClick={handleClick} /&gt;<br>        &lt;/div&gt;<br>    );<br>};<br><br>export default ParentComponent;<br><br>const ChildComponent = React.memo(({ onClick }) =&gt; {<br>    console.log(&#39;Child component rendered&#39;);<br>    return &lt;button onClick={onClick}&gt;Click me&lt;/button&gt;;<br>});</pre><p>Now, ChildComponent will only re-render when its props change, not when ParentComponent re-renders. The onClick function prop is cached using useCallback, and since its dependency array is empty, it will retain the same reference across re-renders. This means that ChildComponent will only render the first time and will not re-render when for example the count state in ParentComponent changes.</p><p>So as we see, to avoid unnecessary child component re-renders, using only useMemo or useCallback isn’t enough. Wrapping a child in React.memo is also pointless if you’re not passing any props. While useMemo and useCallback can optimize calculations or callback functions, they won’t prevent child re-renders on their own unless combined with React.memo.</p><h3>Refactoring Context Provider with Performance in Mind</h3><p>I’m currently building a time management app for myself. It’s not a simple app, but it’s also not too complex yet — the functionality is still somewhat advanced.</p><p>I’m using React Context to share data across different components, particularly for the Timer and Settings components and I’m saving the settings and timer information in local storage for now. I plan to move the settings to a database later, though.</p><p>What I want is to show two versions of the context. While there have been many iterations, these two versions highlight significant differences in terms of optimization, structure, and decoupling.</p><h4>Basic Context Implementation</h4><pre>export const TimerProvider: React.FC&lt;{ children: ReactNode }&gt; = ({ children }) =&gt; {<br>  const [timer, setTimer] = useLocalStorage&lt;TimerState&gt;(&#39;timer&#39;, {<br>    activeTab: &quot;work&quot;,<br>    //Other properties<br>  }, true);<br><br>  const [settings, setSettings] = useLocalStorage&lt;TimerSettings&gt;(&#39;timer-settings&#39;, {<br>    isRunning: false,<br>    //Other properties<br>  }, true);<br><br>  // Timer control functions<br>  const startTimer = () =&gt; {<br>    setSettings(prev =&gt; ({ ...prev, isRunning: true }));<br>  };<br><br>  const pauseTimer = () =&gt; {<br>    setSettings(prev =&gt; ({ ...prev, isRunning: false }));<br>  };<br><br>  const setActiveTab = (activeTab: string) =&gt; {<br>    setTimer(prev =&gt; ({ ...prev, activeTab }));<br>  };<br><br>  //Other methods<br><br>  const timerControls = {<br>    startTimer,<br>    pauseTimer,<br>    setActiveTab,<br>    //Other methods<br>  };<br><br>  const settingsControls = {<br>    updateWorkSessions,<br>    updateWorkDuration,<br>    setAutoRest,<br>    //Other methods<br>  };<br><br>  return (<br>    &lt;TimerStateContext.Provider value={timer}&gt;<br>      &lt;SettingsStateContext.Provider value={settings}&gt;<br>        &lt;TimerControlsContext.Provider value={timerControls}&gt;<br>          &lt;SettingsControlsContext.Provider value={settingsControls}&gt;<br>            {children}<br>          &lt;/SettingsControlsContext.Provider&gt;<br>        &lt;/TimerControlsContext.Provider&gt;<br>      &lt;/SettingsStateContext.Provider&gt;<br>    &lt;/TimerStateContext.Provider&gt;<br>  );<br>};</pre><p>It’s a simple approach, and it works, but it has several issues that make it inefficient, for example — since objects and functions are recreated on each render, it leads to unnecessary re-renders of consuming components, also settings and timer logic are bundled together and it would be better to split them into separate files for better readability.</p><p>Let’s go into more detail about the problems — when we pass an object as the value to a React Context provider, React performs a shallow comparison (Shallow comparison in React checks if two values are the same by comparing their references, not their contents) to check if the value has changed. Each time provider renders a new value object is created, even if the object’s content stays the same, this happens because objects are reference types in JavaScript. This causes React to think the context value is different, which can trigger re-renders in all components consuming the context, even if they don’t actually depend on the changed value.</p><p>For example, if the setActiveTab function updates the timer state, the provider re-renders, causing all context values to be recreated with a new reference. This leads to unnecessary re-renders in components that consume other values, even if they don&#39;t rely on the updated timer state.</p><p>This is why using useMemo is important — it memoizes the value so that React only passes a new object when its actual contents change, preventing unnecessary re-renders of consuming components, but its only relevant for reference types and not primitives like a string.</p><h4>Refactored and Optimized Version</h4><pre>export const TimerProvider: React.FC&lt;TimerProviderProps&gt; = ({ children }) =&gt; {<br>  const [timerState, setTimerState] = useLocalStorage&lt;TimerState&gt;(&quot;timer&quot;, {<br>    activeTab: &quot;work&quot;,<br>    isRunning: false,<br>    //Other properties<br>  });<br><br>  const [timer, timerDispatch] = useReducer(timerReducer, timerState);<br><br>  const memoizedTimerState = useMemo(() =&gt; timer, [timer]);<br><br>  const timerControls = useMemo(() =&gt; ({<br>    startTimer: () =&gt; timerDispatch({ type: &quot;START_TIMER&quot; }),<br>    setActiveTab: (activeTab: string) =&gt; timerDispatch({ type: &quot;SET_ACTIVE_TAB&quot;, payload: activeTab }),<br>    //Other methods<br>  }), []);<br><br>  return (<br>    &lt;TimerStateContext.Provider value={memoizedTimerState}&gt;<br>      &lt;TimerControlsContext.Provider value={timerControls}&gt;<br>          {children}<br>      &lt;/TimerControlsContext.Provider&gt;<br>    &lt;/TimerStateContext.Provider&gt;<br>  );<br>};</pre><p>In this example, I’m showing a shortened version of the Timer provider file. There are additional methods and logic that aren’t relevant to this article, so I’ve left them out for clarity. So I’ve organized the timer and settings by moving them into separate files, this separation improves code organization and readability. <em>I’m only showing the timer here.</em></p><p>Additionally, in this refactor version, we’re using a useReducer hook for managing the state and dispatching actions. One advantage of using a reducer is that dispatch functions are stable and don’t change between re-renders, so they don’t need further optimization. So these functions won’t be recreated on every render, reducing the risk of unnecessary re-renders while still providing efficient updates to the state.</p><p>Using useMemo to memoize values and the stable dispatch functions from the reducer helps to minimize unnecessary re-renders of consuming components and to optimize state updates without additional complexity in the useMemo dependencies.</p><p>For example — when the setActiveTab function is called, it updates the timer state, causing the TimerProvider to re-render. However, since timerControls is wrapped in useMemo with an empty dependency array, it retains the same reference across renders and is not recalculated when the timer state changes. Additionally, because we are using dispatch functions that remain stable, there’s no need to memoize them or include them as dependencies in useMemo. This ensures efficient updates without unnecessary re-renders of components that rely on timerControls<strong>.</strong></p><p>React offers powerful tools for making our apps faster and more efficient. The key is to use these tools correctly. Don’t try to optimize everything right away. Start with simple code, then add these techniques where they’re really needed. Remember, over-optimization can sometimes slow things down instead of speeding them up.</p><p>That being said, I genuinely welcome feedback and different perspectives. Performance optimization in React is a topic with many potential approaches, and I would love to hear how others address it in their projects.</p><p><em>Also, check out my article about the </em><a href="https://medium.com/@EleneSh/78a51b1815f2"><strong><em>React Compiler</em></strong></a><strong><em> </em></strong><em>to learn about the future of performance optimization in React.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc50f91463b6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Functional Programming Concepts for React Developers]]></title>
            <link>https://blog.stackademic.com/how-functional-programming-benefits-react-developers-52824a3a4f44?source=rss-24db65291ea3------2</link>
            <guid isPermaLink="false">https://medium.com/p/52824a3a4f44</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[high-order-functions]]></category>
            <category><![CDATA[pure-function]]></category>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[Elene Shengelia]]></dc:creator>
            <pubDate>Wed, 17 Jul 2024 12:15:48 GMT</pubDate>
            <atom:updated>2024-07-19T00:13:54.374Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rp3AZQi-Rr5yGQjW" /><figcaption>Photo by <a href="https://unsplash.com/@lautaroandreani?utm_source=medium&amp;utm_medium=referral">Lautaro Andreani</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>My goal in this article is to introduce the basics of functional programming and how React developers use FP principles and techniques without necessarily knowing the underlying ideas. I will try to demonstrate simple common React examples where these techniques and principles are applied.</p><p>But first, let’s start with the formal explanation of FP — <em>Functional programming (FP) is a programming language paradigm that treats computation as the evaluation of mathematical functions and avoids changing-state and mutable data.</em></p><p>In simpler terms, functional programming (FP) treats programming like solving math problems with functions that don’t change things around and always give the same answers for the same questions. FP uses functions and immutability (data that can’t change) to write more predictable, easy-to-read, and testable code. Here are some fundamental concepts of FP, on which the whole paradigm is built:</p><ul><li>Immutability — refers to data that can’t change after its creation, like variables or objects. This helps to avoid potential problems, for example debugging — tracking down where and how data changed, can be difficult.</li><li>First class functions — means that functions can be treated like any other variables, you can pass functions as arguments to other functions, return them from other functions, and assign them to variables. This allows us to use them in flexible and powerful way.</li><li>Pure functions — pure functions are easy to test, because they always gives us same output for the same input. It’s like simple math formula f(x) = x+2, every time you use it, if you put in the same number for x, you’ll always get the same result.</li><li>A higher-order function (HOF) — is a function that takes another function as an argument or returns a function. Think of it as combining functions to add more functionality and make a more powerful one.</li></ul><p>In each section of this article, I will explain some functional programming principles that are relevant for React and are used by React developers, sometimes without realizing which paradigm they are using or why it is beneficial.</p><p>Before that let’s talk briefly why understanding FP matters in React — The importance of functional programming in React has grown since the introduction of functional components and hooks in React 16.8. Before this, React used class-based components, which aligned more closely with object-oriented programming paradigms.</p><h4><strong>Declarative Programming</strong></h4><p>Functional programming is a subset of declarative programming, which is a style of coding where you focus on describing what you want to achieve rather than specifying each step to get there (imperative).</p><p>Let’s see simple example of declarative and imperative programming</p><pre>//Imperative<br>const numbers = [1, 2, 3, 4, 5, 6];<br>const evenNumbers = [];<br><br>for (let i = 0; i &lt; numbers.length; i++) {<br>  if (numbers[i] % 2 === 0) {<br>    evenNumbers.push(numbers[i]);<br>  }<br>}<br><br>//Declarative<br>const numbers = [1, 2, 3, 4, 5, 6];<br>const evenNumbers = numbers.filter(number =&gt; number % 2 === 0);<br></pre><p>We can use filter method instead of a traditional for loop to perform operations on arrays. With filter, you specify a condition in a callback function (in our example finding all even numbers in array) and JS takes care of rest — so you’re expressing what you want to achieve rather than specifying each step (see imperative for loop example).</p><p>When we write React components, we often adopt a declarative approach. This means we specify what should appear on the screen based on changes in the component’s state, React then handles the process of updating the actual DOM to reflect these changes. This way, we focus on describing how the UI should look in different states, and React doing DOM manipulations for us.</p><p>Let’s see a simple example: many developers have written to-do list applications using a declarative coding style in React, where the UI updates automatically based on changes in state, such as tasks being added or completed.</p><pre>import React, { useState } from &#39;react&#39;;<br><br>const TaskList = () =&gt; {<br>  const [tasks, setTasks] = useState([<br>    { id: 1, text: &#39;Learn React&#39; },<br>    { id: 2, text: &#39;Learn FP&#39; },<br>  ]);<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h2&gt;Task List&lt;/h2&gt;<br>      &lt;ul&gt;<br>        {tasks.map(task =&gt; (<br>          &lt;li key={task.id}&gt;{task.text}&lt;/li&gt;<br>        ))}<br>      &lt;/ul&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default TaskList;</pre><p>This code showcases a declarative style of programming. Instead of giving step-by-step instructions on how to update the DOM, we’re simply describing what we want the UI to look like based on the current state. We tell React, “Here’s what the task list should look like when we have these tasks” and React figures out how to make it happen.</p><h4><strong>Pure Functions</strong></h4><p>We can call pure functions, those which always produce the same output for the same input and do not have any side effects. We can say that pure functions reflect mathematical functions, always producing the same result for the same input — f(x) = x+2, you will always get same output for the same x.<strong> </strong>Simple example can be double function, which will always returns number * 2 for number input.</p><pre>function double(number) {<br>  return number * 2;<br>}</pre><p>Now that we understand the idea behind the pure functions, we can see similar principles to React components, known as pure components. In React, a pure component is like a pure function — it always produces the same UI for the same input prop.</p><pre>import React from &#39;react&#39;;<br><br>const Button = ({ onClick, label }) =&gt; {<br>  return (<br>    &lt;button onClick={onClick}&gt;<br>      {label}<br>    &lt;/button&gt;<br>  );<br>};<br><br>export default Button;</pre><p>This Button component is a perfect example of a pure component in React. It&#39;s pure because it always renders the same output for the same input props. No matter how many times you use this component with the same onClick function and label text, it will always produce the same button. The component doesn&#39;t change any external state or have any side effects. It simply takes in props and returns JSX based on those props</p><h4>Closures</h4><p>Functional programming principles are built upon foundational concepts like closures.</p><p>Closures are created when a function is defined inside another function, and the inner function retains access to the variables in the outer function’s scope, even after outer function has finished executing.</p><p>Maybe now you see how this applies to React: when you define hooks or functions inside a component, they form closures, remembering and accessing the component’s state, variables and props even after the component renders.</p><p>Let’s look at a simple example: a list component where we return some JSX for the list and add a click handler to each item.</p><pre>import React, { useState } from &#39;react&#39;;<br><br>const ItemList = ({ items }) =&gt; {<br>  const [selectedItem, setSelectedItem] = useState(null);<br>  const handleItemClick = (item) =&gt; () =&gt; {<br>    setSelectedItem(item);<br>  };<br><br>  return (<br>    &lt;div&gt;<br>      &lt;ul&gt;<br>        {items.map((item) =&gt; (<br>          &lt;li<br>            key={item.id}<br>            onClick={handleItemClick(item)}<br>          &gt;<br>            {item.name}<br>          &lt;/li&gt;<br>        ))}<br>      &lt;/ul&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default ItemList;</pre><p>handleItemClick is a double arrow function. The outer arrow function (handleItemClick) takes an item as an argument and returns another arrow function.</p><ul><li>When the ItemList component renders, the outer handleItemClick function runs and captures the specific item.</li><li>When you click on a list item, the inner function runs, and it still has access to the item captured by the outer function (because of closures) even though outer function has finished executing.</li></ul><p>So basically the inner arrow function (the one returned by handleItemClick) is the actual event handler for the list item.</p><p>This ensures that each list item maintains its own context without affecting others.</p><p>Without closures, we wouldn’t have the ability to create hooks that remember state between renders, or event handlers that access the latest component state. This concept allows React components to maintain their own “memory” and behavior, making it possible to build complex, interactive UIs where each piece of functionality is encapsulated within its component.</p><h4>Currying</h4><p>The handleItemClick function in the example above also demonstrates a technique in functional programming known as currying — it’s a technique where a function with multiple arguments is broken down into a series of functions and each take one argument.</p><p>Let’s see simple currency converter example:</p><pre>const convertCurrency = (rate) =&gt; (amount) =&gt; (fees) =&gt; {<br>  const convertedAmount = amount * rate;<br>  return convertedAmount + fees;<br>};<br><br>const usdToEuro = convertCurrency(0.85);<br>// Usage<br>console.log(usdToEuro(100)(5));</pre><p>first, we set the exchange rate, then the amount, and finally any fees. This way, you can reuse parts of the process without starting over. So we can reuse usdToEuro multiple times with different amounts and fees without repeating the exchange rate.</p><p>So currying means breaking down a function that takes multiple inputs into a chain of functions, each handling one input at a time. It’s important because as we saw in above example it makes functions more flexible and reusable, allowing you to set up part of a calculation and fill in the rest later.</p><p>We can see more specific example how currying simplifies event handling in React by allowing us to create specialized functions for handling different events.</p><pre>import React from &#39;react&#39;;<br><br>const ButtonComponent = () =&gt; {<br>  const handleButtonClick = (buttonType) =&gt; (event) =&gt; {<br>    if (buttonType === &#39;firstButton&#39;) {<br>      console.log(&#39;Clicked the first button!&#39;);<br>    } else if (buttonType === &#39;secondButton&#39;) {<br>      console.log(&#39;Clicked the second button!&#39;);<br>    }<br>  };<br><br>  return (<br>    &lt;div&gt;<br>      &lt;button onClick={handleButtonClick(&#39;firstButton&#39;)}&gt;First Button&lt;/button&gt;<br>      &lt;button onClick={handleButtonClick(&#39;secondButton&#39;)}&gt;Second Button&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default ButtonComponent;</pre><p>In this React component, handleButtonClick is a curried function that capturs the button type (buttonType) at the time of its creation. When the onClick event occurs on each button, React executes the corresponding curried function. So instead of managing multiple separate event handlers, you create a modular and organized structure that is easier to maintain and extend.</p><h4>Higher-Order Functions (HOFs)</h4><p><strong>Higher-Order Functions — </strong>are functions that either take one or more functions as arguments or return a function. HOFs enable functional programming techniques such as currying and function composition.</p><p>In React, <strong>Higher-Order Components (HOCs)</strong> are functions that take a component and return a new component with added functionality. They’re useful because they let developers reuse code logic across their projects, reducing repetition and making code more optimized and readable.</p><p>To illustrate the functionality of HOCs, we can create a simple example for fetching data. We are using HOFs and also Currying technique to demonstrate use cases of both.</p><pre>// Curried HOC for fetching data<br>const withDataFetching = (url) =&gt; (WrappedComponent) =&gt; {<br>  return () =&gt; {<br>    const [data, setData] = useState(null);<br>    const [error, setError] = useState(null);<br><br>    useEffect(() =&gt; {<br>      const fetchData = async () =&gt; {<br>        try {<br>          const response = await fetch(url);<br>          if (!response.ok) {<br>            throw new Error(&#39;Failed to fetch data&#39;);<br>          }<br>          const result = await response.json();<br>          setData(result);<br>        } catch (error) {<br>          setError(error);<br>        }<br>      };<br>      fetchData();<br>    }, [url]);<br>    return &lt;WrappedComponent data={data} error={error} /&gt;;<br>  };<br>};</pre><pre>// Component to be wrapped<br>const DisplayData = ({ data, error }) =&gt; {<br>  if (error) {<br>    return &lt;p&gt;Error: {error.message}&lt;/p&gt;;<br>  }<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h2&gt;Data:&lt;/h2&gt;<br>      &lt;pre&gt;{JSON.stringify(data, null, 2)}&lt;/pre&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>// Wrapped component with data fetching<br>const DataComponent = withDataFetching(url)(DisplayData);</pre><p>The withDataFetching function is a Higher-Order Component (HOC) designed to fetch data from a specified URL and pass it as props to a wrapped component. It manages the data retrieval process using the useState and useEffect hooks to update the component&#39;s state with fetched data or handle errors if the request fails. By using this HOC, components like DisplayData can focus solely on displaying data and handling errors without worrying about data fetching logic.</p><p>In modern React development we can achieve same (fetching) functionality with custom hooks. Both HOCs and custom hooks are great tools for sharing logic between components. But custom hooks offer a simpler and more direct approach to managing stateful logic, especially for tasks like fetching data asynchronously. They encapsulate this logic in a way that’s easier to understand.</p><p><strong>Same example with custom hook:</strong></p><pre>const useDataFetching = (url) =&gt; {<br>  const [data, setData] = useState(null);<br>  const [error, setError] = useState(null);<br><br>  useEffect(() =&gt; {<br>    const fetchData = async () =&gt; {<br>      try {<br>        const response = await fetch(url);<br>        if (!response.ok) {<br>          throw new Error(&#39;Failed to fetch data&#39;);<br>        }<br>        const result = await response.json();<br>        setData(result);<br>      } catch (error) {<br>        setError(error);<br>      }<br>    };<br>    fetchData();<br>  }, [url]);<br>  return { data, error };<br>};</pre><p>Then we can use it in component:</p><pre>const { data, isLoading, error } = useDataFetching(&#39;&#39;);</pre><p>Generally, choosing between custom hooks and HOCs depends on what you’re trying to do. For example, hooks are great for sharing and reusing logic between components or for handling tasks like fetching data. This article focuses on understanding functional programming (FP) principles and techniques, especially within the context of React, it does not cover specific topics such as why modern React often favors hooks for many tasks — so understanding Higher-Order Components is valuable for learning functional programming concepts in React.</p><h4>Immutability</h4><p>Immutability means that once an object is created, it cannot be changed directly. Instead, you create a new object by copying the old one and making any necessary changes.</p><p>In React, immutability is crucial for several reasons, for example it is related to performance optimizations using shallow comparisons. Shallow comparison checks if two values (like objects or arrays) reference the same location in memory. When React components re-render when their state or props change, React quickly checks if the new state or props are different from the previous ones using a shallow comparison — if it’s different performs re-rendering.</p><p>When managing state in React, it’s important to update state immutably to ensure predictable behavior and optimize performance. Here’s how it works:</p><pre>  const [user, setUser] = useState({<br>    name: &#39;John&#39;,<br>    address: {<br>      country: &#39;USA&#39;,<br>      city: &#39;New York&#39;,<br>    }<br>  });<br><br>  setUser(prevUser =&gt; ({<br>     ...prevUser,<br>     address: {<br>       ...prevUser.address,<br>       city: &#39;San Francisco&#39;<br>     }<br>  }));</pre><p>Instead of directly modifying the address object, the updater function creates a copy of the previous state (prevUser) using the spread operator (...prevUser). This approach ensures that modifications are applied immutably and React can efficiently manage state changes and trigger re-renders only when necessary.</p><p>By following and understanding these functional programming principles, as React developers, we can create more predictable, reusable, and efficient applications.</p><p><em>I very much welcome feedback, other viewpoints, and discussions on this topic.</em></p><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a></li><li>Visit our other platforms: <a href="https://plainenglish.io/"><strong>In Plain English</strong></a> | <a href="https://cofeed.app/"><strong>CoFeed</strong></a> | <a href="https://differ.blog/"><strong>Differ</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52824a3a4f44" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/how-functional-programming-benefits-react-developers-52824a3a4f44">Functional Programming Concepts for React Developers</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why You Should Use Drupal with Next.js and How to Get Started]]></title>
            <link>https://blog.stackademic.com/why-you-should-use-drupal-with-next-js-and-how-to-get-started-6a91cecd772a?source=rss-24db65291ea3------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a91cecd772a</guid>
            <category><![CDATA[drupal]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[headless-cms]]></category>
            <dc:creator><![CDATA[Elene Shengelia]]></dc:creator>
            <pubDate>Fri, 23 Feb 2024 13:07:39 GMT</pubDate>
            <atom:updated>2024-07-19T00:15:50.682Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fr9soikg7EJ--PSvQXhLRg.jpeg" /></figure><p>This is my series of articles about Drupal, Next.js, and generally how to use headless CMS as a frontend developer to build full-stack apps (or maybe for Drupal developers who don’t have experience with frontend). Please check the first part of the article <a href="https://medium.com/@EleneSh/why-next-js-drupal-simplifies-frontend-development-with-headless-cms-integration-b6b20a11c0ca">here </a>if you haven’t already.</p><p>In this article, we’ll explore how to utilize Drupal as a Headless CMS alongside Next.js to build a full-stack web application, with the help of <a href="https://next-drupal.org/docs">Next.js for Drupal</a>. We’ll walk through the process of setting up Drupal as the backend, configuring Next.js for the frontend, creating content types in Drupal, implementing path aliases, and fetching content in Next.js. By following this step-by-step guide, frontend developers can start a full-stack app in just several hours.</p><p>Below is a diagram representing roughly how Headless Drupal and Next.js work together:</p><figure><img alt="Headless CMS flowchart" src="https://cdn-images-1.medium.com/max/921/1*jKwIdm7s7Hn0XgPJRTCS8w.png" /></figure><p>We’ll be using <a href="https://docs.docker.com/">Docker </a>and <a href="https://ddev.readthedocs.io/en/stable/">DDEV </a>alongside to handle all the backend configurations effortlessly. But before that, let’s briefly discuss Docker and DDEV.</p><p><strong>Docker </strong>is like a virtual container that holds everything your app needs to run smoothly — from code to libraries to dependencies. It ensures that your app behaves consistently no matter where it’s deployed, making development and deployment easier.</p><p><a href="https://ddev.readthedocs.io/en/stable/"><strong>DDEV</strong></a>, on the other hand, is a higher-level tool that builds on top of Docker to provide a user-friendly interface for managing development environments. It automates many of the tasks involved in setting up a development environment, such as configuring web servers, databases, and other services. DDEV simplifies the process of working with Docker specifically for web development projects.</p><p>DDEV is your go-to tool that simplifies the process of setting up and configuring all the essential backend components like PHP, databases, and more. With DDEV, you can say goodbye to the headache of manual installations and focus more on your frontend tasks. DDEV makes it easier for developers to work with Docker and quickly get up and running with their projects, especially for those who may not be as familiar with Docker’s lower-level commands and configurations.</p><h3>Installing DDEV and Docker</h3><p>Before installing DDEV we should install docker on our machine, installation instruction is different based on your Operating System.</p><p>I have windows, so I followed WSL2 installation guide. If you’re also on Windows, I recommend using Docker Desktop for faster performance and to avoid potential timeout errors, which I’ve encountered when using Docker inside WSL.</p><p>You can follow the Docker and DDEV installation instructions based on your system.</p><p><strong>Install Docker</strong>:</p><ol><li><a href="https://ddev.readthedocs.io/en/stable/users/install/docker-installation/#__tabbed_1_2">Linux</a></li><li><a href="https://ddev.readthedocs.io/en/stable/users/install/docker-installation/#__tabbed_1_3">Windows</a></li><li><a href="https://ddev.readthedocs.io/en/stable/users/install/docker-installation/#__tabbed_1_1">MacOS</a></li></ol><p><strong>Install DDEV</strong>:</p><ol><li><a href="https://ddev.readthedocs.io/en/stable/users/install/ddev-installation/#__tabbed_1_2https://ddev.readthedocs.io/en/stable/users/install/ddev-installation/#__tabbed_1_2">Linux</a></li><li><a href="https://ddev.readthedocs.io/en/stable/users/install/ddev-installation/#__tabbed_1_3">Windows</a></li><li><a href="https://ddev.readthedocs.io/en/stable/users/install/ddev-installation/#__tabbed_1_1">MacOS</a></li></ol><p>If everything is okay, we can now use the Ubuntu Terminal app to execute our project using DDEV.</p><p>You can either follow the DDEV guide at<a href="https://ddev.readthedocs.io/en/stable/users/quickstart/"> https://ddev.readthedocs.io/en/stable/users/quickstart/</a> for Drupal, or clone <a href="https://github.com/elenesheng/next-drupal-example">my repository</a> and initiate the project by following the instructions outlined in the README.md file.</p><p><strong>Setting Up Next.js for Drupal composer package</strong></p><p>If you follow the DDEV documentation for installing Drupal, you’ll need to install the Next.js for Drupal Composer package:</p><pre>composer require drupal/next</pre><p>Then you will need to apply patches to fix conflicts and issues, so open your Drupal composer package and add patches:</p><pre>&quot;extra&quot;: {<br>   &quot;patches&quot;: {<br>       &quot;drupal/subrequests&quot;: {<br>           &quot;Get same results on different request&quot;: &quot;https://www.drupal.org/files/issues/2019-07-18/change_request_type-63049395-09.patch&quot;<br>       },<br>       &quot;drupal/decoupled_router&quot;: {<br>           &quot;Unable to resolve path on node in other language than default&quot;: &quot;https://www.drupal.org/files/issues/2022-11-30/decouple_router-3111456-resolve-language-issue-58.patch&quot;<br>       }<br>   },<br>}</pre><p>Then run following command:</p><pre>composer require cweagans/composer-patches</pre><p>Next, you should enable modules from the Drupal admin panel. The required module is Next.js, and then you can activate either the JSON API or GraphQL module. The choice is yours. In this example, we will use JSON API. To do this, activate the “Next.js JSON:API” module. You can do this by visiting “admin/modules” or by selecting “Extend” from the top menu bar in Drupal, then searching for the desired module names and following the instructions to activate them.</p><h3>Configuring Next.js</h3><p>After activating the modules, we’ll proceed to configure Next.js.</p><p>To create the Next.js project, we can use the Next.js for Drupal basic starter. Some configuration will already be set up for us. Run the following command in your Next.js Frontend folder:</p><pre>npx create-next-app -e https://github.com/chapter-three/next-drupal-basic-starter</pre><blockquote><em>Before continuing, configure the Next.js site from the Drupal admin panel by navigating to /admin/config/services/next. Press ‘Add Next.js site’ and follow the instructions. Additionally, to generate DRUPAL_CLIENT_ID and DRUPAL_CLIENT_SECRET, you can retrieve them from /admin/config/services/consumer.</em></blockquote><p>Now create .env.local file in your Next.js project and duplicate the contents of .env.example into it. Be sure to update constants like NEXT_PUBLIC_DRUPAL_BASE_URL with your Drupal URL. You can retrieve these variables from the Drupal site&#39;s admin panel at admin/config/services/next since we have already added the Next.js site. Simply press &quot;environment variables&quot; and copy the content.</p><p>Please add the following line to your .env file:</p><pre>NODE_TLS_REJECT_UNAUTHORIZED=0</pre><p>This is necessary because our Drupal site configured with DDEV is running on HTTPS, and without this line, you will encounter the error “unable to verify the first certificate.” This issue won’t occur when you deploy to a production server with a valid certificate.</p><p>Once done, start your Next.js project.</p><p>Now that your Backend and Frontend are configured, we need to perform some tasks in the admin panel and in the FE to set up our small blog site.</p><h3>Creating Content Type in Drupal</h3><p>First, we will create <strong>News </strong>content type and let’s start by clarifying what a content type is in Drupal and why we need it:</p><p>In Drupal, a content type serves as a blueprint for organizing and displaying various types of information on your website. Content types allow us to establish a structure for each type of content and utilize different fields or reuse fields from other content types. Essentially, content types help us organize different kinds of information on our website.</p><p>To create a content type in Drupal, navigate to /admin/structure/types in your admin panel, or choose &quot;Structure&quot; and then &quot;Content types&quot; from the Drupal top bar menu. You&#39;ll notice that some content types are already pre-made by Drupal, such as articles and basic pages.</p><p>For this example, let’s create a content type for “News.” While we could easily use the pre-made “Article” content type, for educational purposes, let’s create a new one. Click on “Add content type” and provide basic information for this content type. For instance, set the title to “News” and provide a brief description:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/1*hiAnMWcovXNQbEY7kT8_zw.png" /></figure><p>After providing the basic information for the “News” content type, click on “Save and manage fields.” From here, we will create or reuse already created fields for our content type.</p><p>For the “News” content type, let’s say we need the following fields: title, body, and listing image.</p><p>Since the body field is already created for us, we only need to add the listing image field. To do this, create a new field. The field type should be “Image,” and let’s use the title “Listing Image.” Additionally, take note of the machine name for this field, which in our case is field_listing_image.</p><p>Great! Now that we’ve created our first content type, let’s move on to configuring path aliases.</p><h3>Configuring Path Aliases in Drupal</h3><p>So, what exactly is a path alias and why do we need to configure it?</p><p>In Drupal, a path alias is like giving a nickname or an easy-to-remember name to a specific page or content item on your website. Instead of using the default URL, which might be complicated, you can create more human-readable version.</p><p>For example, imagine you have a news article on your website about “New Technology Trends.” The default URL might look something like this: www.yourwebsite.com/node/123. That&#39;s not very friendly. With path aliases, you can create a custom URL like this: <a href="http://www.yourwebsite.com/news/new-technology-trends.">www.yourwebsite.com/news/new-technology-trends.</a></p><p>Alright, to configure path aliases, follow these steps:</p><ul><li>Visit admin/config/search/path/.</li><li>In the top menu, select “Patterns.” Here, we’ll create a path pattern for our “News” content type.</li><li>Select “Content” for the pattern type.</li><li>Choose our newly created “News” content type</li><li>In the “Path pattern” field, enter something like this: news/[node:title].</li></ul><p>Let’s break down this pattern:</p><ul><li>news: This is the prefix or base path you&#39;ve chosen for your &quot;News&quot; content type. It indicates that all news articles will have URLs that start with /news/.</li><li>[node:title]: This is a token that Drupal replaces with actual content when generating the URL. Specifically, [node:title] means it will use the title of the content node to complete the URL. For example, if you have a news article with the title &quot;New Technology Trends,&quot; the URL for that article would be something like /news/new-technology-trends.</li></ul><p>So, Drupal uses this path pattern to automatically generate URLs for content of the “News” content type based on the title of each individual news article.</p><p>Your pattern will look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/575/1*UZ-awgZ6NPiFK0fmPwO1Sg.png" /></figure><p>Alright, let’s proceed with adding several news articles:</p><ol><li>Go to “Content” and click on “Add content.”</li><li>Choose “News” for the content type.</li><li>Fill in the fields with the relevant information for each news article.</li><li>The URL will be automatically generated for us because we’ve already added a path pattern for our news content type.</li></ol><p>Now that we have our content type set up for our news page, let’s move on to fetching this content in our Next.js Frontend and choose a fetching strategy.</p><h3>Fetching Content in Next.js</h3><p>As a Next.js developer, you should be familiar with the different fetching strategies Next.js offers. Let’s briefly discuss each one:</p><ol><li>Static Generation (SG): Generates HTML pages at build time. Use it for content that doesn’t change often and can be pre-rendered.</li><li>Server-side Rendering (SSR): Generates HTML pages on each request. Use it for fresh data on every request.</li><li>Incremental Static Regeneration (ISR): Combines the benefits of Static Generation with the ability to update data without rebuilding the entire site. Use it for data that changes frequently but doesn’t need to be updated in real-time.</li><li>On-demand revalidation — is a feature that allows you to update data dynamically on a page without the need for a full reload. It’s part of Next.js’s Incremental Static Regeneration (ISR).</li></ol><h4>Choosing Incremental Static Regeneration with on-demand revalidation</h4><p>Since our news page is a listing page that will change frequently due to new articles being added, my choice would be Incremental Static Regeneration with on-demand revalidation. This way, the news page will be updated every time content is added or deleted, but without rebuilding the entire site.</p><p>As mentioned in the first article, The Next.js for Drupal makes integrating Next.js’s revalidation strategy with Drupal straightforward and user-friendly.</p><p>So as it written is Nextjs for drupal documentation:<br><a href="https://nextjs.org/docs/basic-features/data-fetching/incremental-static-regeneration#on-demand-revalidation"><em>On-demand Revalidation</em></a><em> makes it easy to update your Next.js site when content on Drupal is created, updated or deleted.</em></p><p><em>Starting with v1.6.0, Next.js for Drupal supports On-demand Revalidation configurable per entity types.</em></p><p><strong><em>First clarify what entity type is in Drupal<br></em></strong><em>In Drupal, an “entity type” is like a category or type of content. Think of it as a template for different kinds of information. In our case, “News” is the entity type. Each news article (or node) created using this content type becomes an instance of the “News” entity type.</em></p><h4>Integrating Next.js revalidation strategy with Drupal</h4><p>In order to trigger revalidation of specific pages (URLs) in Next.js when associated entity types (e.g., news) are manipulated (created/updated/deleted) in Drupal, we’ll use the revalidator plugin. In our case, we’ll utilize the path module, but it’s worth noting that you can also create a custom revalidator plugin if needed. However, for the sake of simplicity and focusing on frontend developers with minimal backend knowledge, we’ll proceed with the path module.</p><p>By configuring the “Path” module as a revalidator plugin, we’ll be able to notify Next.js to revalidate specific pages (URLs) associated with content items (nodes) when those nodes are manipulated (created/updated/deleted) in Drupal. In simpler terms, if we make any changes to content in Drupal, the corresponding URLs will automatically be updated in Next.js.</p><p>In the Drupal admin panel, navigate to /admin/config/services/next and Edit already added &quot;Next.js Site.&quot; Here, you&#39;ll need to provide the necessary information for integrating On-demand revalidation.</p><p>On-demand revalidation:</p><ul><li>URL: Specify the URL endpoint on your Next.js site that handles on-demand revalidation. This URL should correspond to the endpoint you’ll set up in your Next.js project.</li><li>Secret: Use the same secret that you have defined in your Next.js environment. If you haven’t defined the secret in your Next.js environment yet, make sure to define it there first and then use the same secret here.</li></ul><pre>DRUPAL_REVALIDATE_SECRET=secret</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*7OqBE1bHMd2rxS-fmtEy1g.png" /></figure><p>To configure entity types for on-demand revalidation in Drupal, follow these steps:</p><ol><li>Press “Entity Types”.</li><li>Choose “Content type.” For example, if your content type is “News,” select that option.</li></ol><p>This step will allow you to configure the revalidator plugin for the specified content type, enabling on-demand revalidation for entities of that type:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*2B2_24wpsUPFSdIAjtJz4w.png" /></figure><p>The Drupal part is now complete, and the next step is to configure on-demand revalidation in Next.js. While this feature is not included in the basic starter, it’s available in another example. You can find the setup instructions and example code <a href="https://github.com/chapter-three/next-drupal/blob/main/examples/example-marketing/pages/api/revalidate.ts">here</a>. Let’s proceed with integrating this functionality into our project. Create a file named revalidate.ts in the pages/api directory with the following content:</p><pre>import { NextApiRequest, NextApiResponse } from &quot;next&quot;;<br><br>export default async function handler(<br>  request: NextApiRequest,<br>  response: NextApiResponse<br>) {<br>  let slug = request.query.slug as string;<br>  const secret = request.query.secret as string;<br><br>  // Validate the secret.<br>  if (secret !== process.env.DRUPAL_REVALIDATE_SECRET) {<br>    return response.status(401).json({ message: &quot;Invalid secret.&quot; });<br>  }<br><br>  // Validate the slug.<br>  if (!slug) {<br>    return response.status(400).json({ message: &quot;Invalid slug.&quot; });<br>  }<br><br>  if (slug === process.env.DRUPAL_FRONT_PAGE) {<br>    slug = &quot;/&quot;;<br>  }<br><br>  try {<br>    await response.revalidate(slug);<br><br>    return response.json({});<br>  } catch (error) {<br>    return response.status(404).json({<br>      message: error.message,<br>    });<br>  }<br>}</pre><p>This code creates a custom revalidation route in our Next.js app. The route listens for incoming requests and is accessed via the /api/revalidate endpoint. During our Next.js site configuration in the Drupal admin, we specified http://localhost:3000/api/revalidate as the revalidate URL, which corresponds to this route in Next.js.</p><h3>Fetching News Articles from Drupal</h3><p>First, we need to install drupal-jsonapi-params.</p><p>Next, create a file named get-params.ts in the lib folder.</p><p>In this file, we’ll define functions to generate parameters for fetching news articles from Drupal using JSON:API.</p><pre>import { DrupalJsonApiParams } from &quot;drupal-jsonapi-params&quot;;<br><br>// A helper function to build params for a resource type.<br>export function getParams(<br>    name: string,<br>    mode: string<br>): DrupalJsonApiParams {<br>    const params = new DrupalJsonApiParams();<br><br>    name = mode ? `${name}--${mode}` : name;<br>    if (name === &quot;node--news&quot;) {<br>        return params<br>            .addFilter(&quot;status&quot;, &quot;1&quot;)<br>            .addFields(&quot;news&quot;, [&quot;title&quot;, &quot;body&quot;,&quot;field_listing_image&quot;, &quot;created&quot;, &quot;path&quot;, &quot;created&quot;])<br>            .addInclude([<br>                &quot;field_listing_image&quot;,<br>            ]);<br>    }<br>}</pre><p>The provided code defines a helper function, getParams, which constructs and returns a DrupalJsonApiParams object based on the provided resource type (name) and mode. This function utilizes the drupal-jsonapi-params package to interact with a Drupal backend via JSON:API. Depending on the resource type, specific filters, fields, and includes are added to the params object. These parameters are then utilized to fetch data from a Drupal backend using JSON:API within a Next.js application.</p><p>Now create pages/news/index.tsx file:</p><pre>import { GetStaticPropsResult, GetStaticPropsContext } from &quot;next&quot;;<br>import { DrupalNode, JsonApiResponse } from &quot;next-drupal&quot;;<br>import { drupal } from &quot;@/lib/drupal&quot;;<br>import { getParams } from &quot;@/lib/get-params&quot;;<br>import { getGlobalElements } from &quot;@/lib/get-global-elements&quot;;<br><br>interface NewsPageProps {<br>  news: DrupalNode[];<br>}<br><br>export default function NewsPage({ news }: NewsPageProps) {<br>  // Render news items here<br>  return (<br>    &lt;div&gt;<br>      {news.map((item) =&gt; (<br>        &lt;div key={item.id}&gt;{item.title}&lt;/div&gt;<br>      ))}<br>    &lt;/div&gt;<br>  );<br>}<br><br>export async function getStaticProps(<br>  context: GetStaticPropsContext<br>): Promise&lt;GetStaticPropsResult&lt;NewsPageProps&gt;&gt; {<br>  // Fetch all published news items sorted by date.<br>  const news = await drupal.getResourceCollectionFromContext&lt;DrupalNode[]&gt;(<br>    &quot;node--news&quot;,<br>    context,<br>    {<br>      params: getParams(&quot;node--news&quot;, &quot;&quot;)<br>        .addFilter(&quot;status&quot;, &quot;1&quot;)<br>        .addSort(&quot;created&quot;, &quot;DESC&quot;)<br>        .getQueryObject(),<br>    }<br>  );<br><br>  return {<br>    props: {<br>      ...(await getGlobalElements(context)),<br>      news: drupal.deserialize(news) as DrupalNode[],<br>    },<br>  };<br>}</pre><p>And that’s it, we are fetching news from Drupal and using on-demand revalidation.</p><p>To check if on-demand revalidation works on the Next.js side, simply add or update news in Drupal. Then, in your browser, navigate to yoururl/api/revalidate?secret=secret&amp;slug=/news. However, it&#39;s not really necessary to perform this check because with the help of Next.js for Drupal, our content will be automatically updated whenever content is updated in Drupal.</p><p>I believe this article will be helpful to developers looking to integrate Drupal with Next.js. It focuses specifically on the practical aspects of using Drupal as a Headless CMS and choosing the appropriate fetching strategy within a Next.js application. While some features are not extensively covered here, as they are well-explained in the Next.js for Drupal documentation, the article aims to provide a concentrated guide on utilizing Drupal and selecting the most suitable fetching approach.</p><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a></li><li>Visit our other platforms: <a href="https://plainenglish.io/"><strong>In Plain English</strong></a> | <a href="https://cofeed.app/"><strong>CoFeed</strong></a> | <a href="https://differ.blog/"><strong>Differ</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a91cecd772a" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/why-you-should-use-drupal-with-next-js-and-how-to-get-started-6a91cecd772a">Why You Should Use Drupal with Next.js and How to Get Started</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Next.js + Drupal Simplifies Frontend Development with Headless CMS Integration]]></title>
            <link>https://blog.stackademic.com/why-next-js-drupal-simplifies-frontend-development-with-headless-cms-integration-b6b20a11c0ca?source=rss-24db65291ea3------2</link>
            <guid isPermaLink="false">https://medium.com/p/b6b20a11c0ca</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[drupal]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[headless-cms]]></category>
            <dc:creator><![CDATA[Elene Shengelia]]></dc:creator>
            <pubDate>Fri, 09 Feb 2024 15:08:46 GMT</pubDate>
            <atom:updated>2024-07-19T00:14:02.051Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lwLdzEB1XE550432Z7AMBw.jpeg" /></figure><p>I’m writing this article to share how using a headless CMS has made a big difference in my work as a freelance front-end developer. I want to show others, especially those who are just starting out, how a headless CMS can help them focus more on front-end tasks without needing extensive backend knowledge.</p><p>First thing first, let’s clarify some of these terms:</p><p><em>A CMS, or Content Management System, is a platform that enables users to create, modify, and remove content easily.</em></p><p><em>A Headless CMS is a type of content management system that separates the content storage and management from the presentation layer, like the website or application front-end. With a Headless CMS, developers have the flexibility to manage content separately from how it’s presented, allowing for easier integration with different front-end technologies and the ability to use the backend solely for API purposes.</em></p><h3>How I incorporated Headless CMS (Drupal) into my work?</h3><p>As a frontend developer, I’ve made the decision to incorporate Drupal into my freelance or personal projects to have a backend solution as well.</p><p>Drupal, a popular CMS, provides both the backend infrastructure for content management and the frontend presentation layer for displaying content to users, however, with the rise of headless CMS architectures, Drupal has adapted to this trend by offering headless capabilities through its built-in RESTful API. This means that instead of relying on Drupal’s built-in frontend templating system, developers can use Drupal as a content repository and interact with its content via APIs.</p><h3>Simplifying Drupal Integration with Next.js: The Next.js for Drupal</h3><p>Drupal’s adoption of the headless CMS model has made it easier to integrate with frontend frameworks like Next.js.</p><p>Drupal and Next.js can be connected using a project called Next.js for Drupal. This project includes a Drupal module and a NPM package, to help interact with Drupal.</p><p>Next.js for Drupal goes a step further by providing seamless integration with Drupal’s RESTful API, adding, for example, content preview functionality. With this feature, users can see real-time previews of content updates directly within their Next.js applications. This not only simplifies the development process but also improves the overall user experience. Additionally, the module offers authentication and other features.</p><p>To kickstart your project, <a href="https://next-drupal.org/learn/quick-start/install-drupal">begin by installing the Next.js for Drupal Composer package</a>. Upon installation, you need to apply patches to resolve any issues and conflicts. Next, activate the required modules: JSON:API or Next.js GraphQL. The choice between <a href="https://www.drupal.org/docs/core-modules-and-themes/core-modules/jsonapi-module/jsonapi">JSON:API</a> or GraphQL is yours, as Next.js for Drupal supports both options.</p><p>Next.js for Drupal provides excellent documentation and tutorials to ensure a smooth setup process. You can find these resources at <a href="https://next-drupal.org/learn/quick-start"><strong>https://next-drupal.org/learn/quick-start</strong></a>. Additionally, there are plenty of examples available on how to integrate Next.js for Drupal into your Next.js front-end. You can explore these examples at<strong> </strong><a href="https://github.com/chapter-three/next-drupal/tree/main/examples"><strong>https://github.com/chapter-three/next-drupal/tree/main/examples</strong></a>.</p><p>Whether you need to set up on-demand revalidation or integrate the Search API into your front-end, you’ll find everything you need to get started with Next.js in these resources.</p><h3>A Summary of Benefits</h3><p>To summarize, using Drupal as a headless CMS with Next.js for Drupal has several benefits that have made my work easier and allowed me to focus on frontend development:</p><ul><li>With Drupal handling content management, I don’t need to create admin forms or worry about database setup.</li><li>Drupal’s built-in RESTful API means I don’t have to build a custom backend.</li><li>With Next.js for Drupal, which offers the DrupalClient class, fetching data and integrating with Drupal has become easy.</li><li>These all and many more have saved me days and weeks</li></ul><h3>Next Steps: Exploring Fetching Strategies and Rendering in Next.js Development</h3><p>Understanding the concepts of server-side and client-side rendering, as well as different fetching strategies, is essential for Next.js development.</p><p>In my upcoming article, I’ll delve into how you can select the most suitable fetching strategies for your Next.js project, and how Next.js for Drupal simplifies this process. But before we dive into that, let’s briefly review the importance of these strategies.</p><p>For example, I believe that the most efficient approach is on-demand revalidation. This method involves regenerating pages only when necessary, such as when content on Drupal is updated, created, or deleted. With this strategy, pages remain up-to-date without unnecessary rebuilding, resulting in enhanced performance and user experience.</p><p><a href="https://next-drupal.org/learn/on-demand-revalidation">The Nextjs for Drupal</a> makes integrating Next.js revalidation strategy with Drupal straightforward and user-friendly. This integration ensures automatic page regeneration when backend content changes, facilitating smooth communication between Drupal and Next.js.</p><p>However, on-demand revalidation may not always be the optimal choice. Depending on your project’s requirements, you might prefer static rendering if the site content changes infrequently.</p><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a></li><li>Visit our other platforms: <a href="https://plainenglish.io/"><strong>In Plain English</strong></a> | <a href="https://cofeed.app/"><strong>CoFeed</strong></a> | <a href="https://differ.blog/"><strong>Differ</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b6b20a11c0ca" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/why-next-js-drupal-simplifies-frontend-development-with-headless-cms-integration-b6b20a11c0ca">Why Next.js + Drupal Simplifies Frontend Development with Headless CMS Integration</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>