<?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 Renan Leonel on Medium]]></title>
        <description><![CDATA[Stories by Renan Leonel on Medium]]></description>
        <link>https://medium.com/@renanleonel?source=rss-76d2ceb73f6c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*n3RBxkk7tO51MlsTgELifQ.jpeg</url>
            <title>Stories by Renan Leonel on Medium</title>
            <link>https://medium.com/@renanleonel?source=rss-76d2ceb73f6c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 07:05:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@renanleonel/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[Mastering React Performance]]></title>
            <link>https://medium.com/@renanleonel/mastering-react-performance-c3d21f85b612?source=rss-76d2ceb73f6c------2</link>
            <guid isPermaLink="false">https://medium.com/p/c3d21f85b612</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[webdev]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[performance]]></category>
            <dc:creator><![CDATA[Renan Leonel]]></dc:creator>
            <pubDate>Thu, 13 Mar 2025 02:27:54 GMT</pubDate>
            <atom:updated>2025-03-13T02:27:54.770Z</atom:updated>
            <content:encoded><![CDATA[<p>Optimizing React apps isn’t always easy — I’ve dealt with slow renders, laggy interactions, and unresponsive UIs more times than I can count. Over time, I’ve learned a range of techniques, from quick fixes to advanced optimizations, that I rely on daily to keep applications fast and responsive. In this guide, I’ll share the most effective ones. By the end, you’ll have practical insights to improve your app’s performance.</p><p>We’ll explore:</p><ol><li>Smart Data Manipulation: Optimizing array operations and data structures</li><li>Strategic Rendering: Preventing unnecessary re-renders</li><li>Advanced Memoization: Using React’s optimization hooks effectively</li><li>Function and Event Optimization: Writing performant event handlers</li><li>Component Virtualization: Efficiently handling large lists</li><li>Data Fetching and Caching: Optimizing API interactions with React Query</li><li>Debouncing and Throttling: Controlling high-frequency events</li><li>Suspense for Data Fetching: Managing asynchronous data efficiently</li></ol><h3>1. Smart Data Manipulation</h3><p>The way we manipulate data can dramatically impact our application’s performance. Small improvements in data handling can lead to significant performance gains, especially when dealing with large datasets.</p><h3>Array Operations Order</h3><p>The order of array operations can significantly impact performance. Consider the difference between map().filter() and filter().map():</p><pre>// Less efficient: Transforms all items, then filters<br>const inefficientResult = largeArray<br>  .map((item) =&gt; transformExpensiveOperation(item))<br>  .filter((item) =&gt; item.isValid);<br><br>// More efficient: Filters first, then only transforms what&#39;s needed<br>const efficientResult = largeArray<br>  .filter((item) =&gt; isValidBeforeTransform(item))<br>  .map((item) =&gt; transformExpensiveOperation(item));</pre><p>When filter() comes first, we avoid unnecessary transformations on items that will be filtered out. This becomes especially important with large datasets or expensive transformations. The performance impact grows with the size of the array and the complexity of the transformation function.</p><p>For example, if you have 10,000 items but only 100 meet your criteria, placing filter() first means you’ll only perform the expensive transformation 100 times instead of 10,000 times. This can be the difference between a smooth experience and a frozen UI.</p><h3>Maps vs. Arrays for Lookups</h3><p>For frequently accessed data, using JavaScript’s Map instead of arrays can provide dramatic performance improvements:</p><pre>// O(n) lookup time - gets slower as array grows<br>const findUserInArray = (users: User[], id: string) =&gt; {<br>  return users.find(user =&gt; user.id === id);<br>};<br><br>// O(1) lookup time - consistent speed regardless of size<br>const findUserInMap = (usersMap: Map&lt;string, User&gt;, id: string) =&gt; {<br>  return usersMap.get(id);<br>};<br><br>// Transform array to Map for repeated lookups<br>const createUsersMap = (users: User[]) =&gt; {<br>  const usersMap = new Map();<br><br>  users.forEach(user =&gt; usersMap.set(user.id, user));<br><br>  return usersMap;<br>};<br><br>// Usage<br>const users = [<br>  /* array of user objects */<br>];<br><br>const usersMap = createUsersMap(users);<br><br>// Fast lookup<br>const user = usersMap.get(&quot;user-123&quot;);</pre><p>The Map data structure offers several advantages over plain objects:</p><ul><li>Better performance for frequent additions and removals</li><li>Keys can be any value (not just strings)</li><li>Built-in size property and iteration methods</li></ul><p>This approach is ideal for data that’s referenced multiple times throughout your application, especially in deeply nested components. The performance difference becomes exponentially larger as your dataset grows.</p><p>Consider a scenario where you frequently need to look up users by ID across multiple components. With an array, each lookup requires iterating through thousands of items, making performance degrade as the dataset grows. In contrast, using a Map enables constant-time lookups, ensuring consistent speed regardless of the number of users. For data-intensive applications, this optimization can drastically improve responsiveness and scalability.</p><h3>Single-Pass Data Transformation</h3><p>Combine multiple operations into a single pass when possible:</p><pre>// Inefficient: Multiple array iterations<br>const filtered = data.filter((item) =&gt; item.active);<br>const transformed = filtered.map((item) =&gt; transform(item));<br>const total = transformed.reduce((sum, item) =&gt; sum + item.value, 0);<br><br>// Efficient: Single pass with reduce<br>const { filtered, transformed, total } = data.reduce(<br>  (result, item) =&gt; {<br>    if (!item.active) return result;<br><br>    const transformedItem = transform(item);<br><br>    result.filtered.push(item);<br>    result.transformed.push(transformedItem);<br>    result.total += transformedItem.value;<br><br>    return result;<br>  },<br>  { filtered: [], transformed: [], total: 0 },<br>);</pre><p>When working with large datasets, each additional iteration through the array adds significant overhead. By using a single-pass approach with reduce(), you traverse the array just once while performing all necessary operations. This technique is particularly valuable for data processing tasks that involve multiple transformations and aggregations.</p><p>The single-pass approach becomes even more valuable when working with server data that needs to be normalized, transformed, and aggregated before being used in your application. It reduces both CPU usage and memory overhead by eliminating intermediate array allocations.</p><h3>2. Strategic Rendering</h3><p>React’s rendering behavior is often the most significant performance bottleneck in complex applications. Understanding how to prevent unnecessary re-renders can dramatically improve your application’s responsiveness.</p><h3>Component Boundaries</h3><p>One of the most effective ways to prevent cascading re-renders is to create strategic component boundaries:</p><pre>// Problematic: Child re-renders when any parent state changes<br>const ParentComponent = () =&gt; {<br>  const [count, setCount] = useState(0);<br>  const [unrelatedState, setUnrelatedState] = useState(false);<br><br>  return (<br>    &lt;div&gt;<br>      &lt;button onClick={() =&gt; setUnrelatedState(!unrelatedState)}&gt;<br>        Toggle unrelated state<br>      &lt;/button&gt;<br><br>      {/* This will re-render even when only unrelatedState changes */}<br>      &lt;div&gt;<br>        &lt;ComplexComponent count={count} /&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>// Improved: Isolated component only re-renders when its props change<br>const ParentComponentImproved = () =&gt; {<br>  const [count, setCount] = useState(0);<br>  const [unrelatedState, setUnrelatedState] = useState(false);<br><br>  return (<br>    &lt;div&gt;<br>      &lt;button onClick={() =&gt; setUnrelatedState(!unrelatedState)}&gt;<br>        Toggle unrelated state<br>      &lt;/button&gt;<br><br>      {/* Isolate the component that depends on count */}<br>      &lt;CountContainer count={count} /&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>// This only re-renders when count changes<br>const CountContainer = React.memo(({ count }) =&gt; {<br>  return &lt;ComplexComponent count={count} /&gt;;<br>});</pre><p>Component boundaries are crucial for performance in large React applications. Each time a component re-renders, all of its children re-render as well, unless specifically optimized. By strategically breaking your UI into smaller components and using React.memo() at key boundaries, you can prevent entire subtrees from re-rendering unnecessarily.</p><p>This becomes especially important for components that:</p><ul><li>Have expensive rendering logic</li><li>Contain many child components</li><li>Display large amounts of data</li><li>Implement animations or visualizations</li></ul><p>Creating these boundaries doesn’t just improve performance — it also leads to more maintainable code by enforcing better separation of concerns and more focused components.</p><h3>Reference Preservation</h3><p>Maintaining stable references is crucial for preventing unnecessary re-renders:</p><pre>// Problematic: New object and function created on every render<br>const Component = () =&gt; {<br>  const options = { sortBy: &quot;name&quot;, limit: 10 };<br>  const handleClick = () =&gt; console.log(&quot;Clicked&quot;);<br><br>  return &lt;ChildComponent options={options} onClick={handleClick} /&gt;;<br>};<br><br>// Improved: Stable references with useMemo and useCallback<br>const ComponentImproved = () =&gt; {<br>  // Memoize options object to keep the reference stable unless dependencies change<br>  const options = useMemo(<br>    () =&gt; ({<br>      sortBy: &quot;name&quot;,<br>      limit: 10,<br>    }),<br>    [],<br>  );<br><br>  // useCallback memoizes the function to avoid re-creating it on each render<br>  const handleClick = useCallback(() =&gt; {<br>    console.log(&quot;Clicked&quot;);<br>  }, []); // empty dependency array ensures the function is memoized once<br><br>  return &lt;ChildComponent options={options} onClick={handleClick} /&gt;;<br>};</pre><p>In React, equality checks for objects and arrays are based on reference comparison, not by value. This means that even if two objects have identical properties, they are treated as distinct if they have different references. For example, {id: 1} === {id: 1} evaluates to false because each object is a separate instance, even though they contain the same data.</p><p>When passing objects or functions as props to memoized components, creating new references on every render defeats the purpose of memoization. React will treat each render as a change, triggering unnecessary re-renders, even if the data itself hasn’t changed.</p><p>This issue affects several common patterns:</p><ul><li>Passing object literals as props</li><li>Creating inline functions in render methods</li><li>Defining arrays inside components</li><li>Creating complex state transformations</li></ul><p>By using hooks like useMemo and useCallback, you can ensure that references remain stable across renders unless dependencies actually change. useMemo helps to memoize the creation of objects or arrays, while useCallback ensures that functions are not recreated unless their dependencies change. This allows React’s memoization mechanisms (such as React.memo) to work effectively, preventing unnecessary re-renders and improving performance throughout your component tree.</p><h3>3. Advanced Memoization</h3><h3>Strategic useMemo Usage</h3><p>Rather than memoizing everything, focus on expensive calculations:</p><pre>// Overkill: Memoizing a simple operation<br>const sum = useMemo(() =&gt; a + b, [a, b]);<br><br>// Appropriate: Memoizing expensive calculations<br>const sortedFilteredData = useMemo(() =&gt; {<br>  return expensiveSort(filterByMultipleConditions(largeDataset, filters));<br>}, [largeDataset, filters]);</pre><p>When considering memoization, always evaluate the cost of the computation versus the cost of memoization itself. Memoization adds memory overhead and some performance cost for dependency comparisons. For simple operations, this overhead might exceed the benefits.</p><p>Memoization is most valuable for:</p><ul><li>Complex sorting or filtering operations</li><li>Data transformations with multiple steps</li><li>Calculations that involve iterating over large arrays</li><li>Derived values that might trigger re-renders when recalculated</li></ul><p>The key is to identify the expensive operations in your application and apply memoization selectively. I generally apply memoization when dealing with operations that are computationally expensive, such as mapping or filtering large datasets, or performing any operation that involves traversing through data and could require another O(n) operation.</p><h3>4. Function and Event Optimization</h3><h3>Defining Functions Outside Components</h3><p>One of the simplest but effective ways to optimize your React components is to define functions that don’t rely on component state or props outside of the component. This prevents these functions from being recreated on every render, improving performance in large applications.</p><p>Consider the following example:</p><pre>// Avoid: Creating a new function on every render<br>const Component = ({ data }) =&gt; {<br>  const formatDate = (date) =&gt; {<br>    return new Date(date).toLocaleDateString();<br>  };<br><br>  return (<br>    &lt;div&gt;<br>      {data.map((item) =&gt; (<br>        &lt;div key={item.id}&gt;{formatDate(item.date)}&lt;/div&gt;<br>      ))}<br>    &lt;/div&gt;<br>  );<br>};<br><br>// Better: Define utility functions outside component scope<br>const formatDate = (date) =&gt; {<br>  return new Date(date).toLocaleDateString();<br>};<br><br>const ImprovedComponent = ({ data }) =&gt; {<br>  return (<br>    &lt;div&gt;<br>      {data.map((item) =&gt; (<br>        &lt;div key={item.id}&gt;{formatDate(item.date)}&lt;/div&gt;<br>      ))}<br>    &lt;/div&gt;<br>  );<br>};</pre><p>When you define functions inside a component, React recreates those functions every time the component re-renders, even if the function’s logic doesn’t depend on any state or props. This can lead to unnecessary memory allocations and could slow down performance, especially in components that re-render frequently.</p><p>Defining functions outside of components eliminates this issue, because the function is created once and remains the same across renders, which helps optimize performance by:</p><ul><li>Reducing the number of new function instances: React no longer needs to recreate the function on every render.</li><li>Making the function reusable: By placing utility functions outside the component, they can be shared across multiple components, reducing code duplication.</li><li>Improving code readability: Keeping the component focused on rendering and separating logic into utility functions makes the component easier to read and maintain.</li><li>Easier to test: By moving logic outside of the component, the functions become easier to test in isolation, improving unit testing efficiency.</li></ul><p>Sometimes, you may need to define a function that depends on state or props within the component. In these cases, you can use the useCallback hook to ensure that the function is not recreated unless its dependencies change. This ensures that the function reference remains stable across renders, preventing unnecessary re-renders in child components that depend on this function.</p><pre>const Component = ({ itemId, onUpdate }) =&gt; {<br>  const handleClick = useCallback(() =&gt; {<br>    onUpdate(itemId);<br>  }, [itemId, onUpdate]);<br><br>  return &lt;button onClick={handleClick}&gt;Update&lt;/button&gt;;<br>};</pre><p>When to use useCallback:</p><ul><li>When you pass a function down to a child component and want to avoid triggering a re-render of the child if the function hasn’t changed.</li><li>When a function depends on specific props or state and you want to ensure it’s only recreated when those specific values change.</li><li>When the function is part of a dependency array of other hooks (like useEffect), and you want to prevent unnecessary re-execution.</li></ul><h3>Handling Event Handlers Efficiently</h3><p>Event handlers are another area where unnecessary re-creations can hurt performance. In React, handlers defined inline (inside JSX) are created every time the component re-renders, leading to a new reference being passed down to child components, which may cause unnecessary re-renders.</p><p>Consider this example:</p><pre>// Avoid: Inline event handlers<br>const Component = ({ onClickHandler }) =&gt; {<br>  return &lt;button onClick={() =&gt; onClickHandler(&quot;clicked&quot;)}&gt;Click me&lt;/button&gt;;<br>};</pre><p>Here, the inline function is re-created on every render. A better approach is to define the handler outside of the JSX to ensure the function reference remains stable across renders:</p><pre>// Better: Use a stable reference for event handlers<br>const Component = ({ onClickHandler }) =&gt; {<br>  const handleClick = useCallback(() =&gt; {<br>    onClickHandler(&quot;clicked&quot;);<br>  }, [onClickHandler]);<br><br>  return &lt;button onClick={handleClick}&gt;Click me&lt;/button&gt;;<br>};</pre><p>This ensures that handleClick maintains the same reference unless onClickHandler changes, reducing unnecessary re-renders in the child component.</p><h3>5. Component Virtualization</h3><p>Virtualization is an important technique for handling large datasets in React applications. Rather than rendering all items at once, virtualization maintains a “window” of rendered elements that dynamically updates as the user scrolls.</p><p>When implementing virtualization in React, you’ll typically need to:</p><ul><li>Track scroll position</li><li>Calculate which items should be visible</li><li>Render only those items</li><li>Position them correctly within the viewport</li></ul><p>Virtualization can provide dramatic performance improvements for lists, tables, grids, and even carousels. For detailed implementation examples, refer to my <a href="https://medium.com/@renanleonel/virtualizing-react-f26361d5960b">Virtualizing React</a> article.</p><h3>6. Data Fetching and Caching</h3><p>If you’re not using React Query in your React applications yet, you probably should be. React Query provides an efficient, declarative approach to handling server state, managing data fetching, and optimizing network requests. Relying on useEffect for client-side data fetching might seem like a straightforward solution, but it’s not the most effective, especially as your application grows in complexity.</p><p>While useEffect can work for simple fetches, it lacks built-in caching, automatic background refetching, and the ability to handle errors and retries seamlessly. React Query abstracts these concerns away, providing a robust, highly customizable solution that not only simplifies data fetching but also optimizes performance with features like caching, pagination, and synchronization.</p><p>By using React Query, you can drastically reduce boilerplate code, improve loading states, and focus more on building the features that matter, all while ensuring data consistency and efficiency.</p><h3>Basic Implementation</h3><p>Here’s how to implement React Query for optimal data fetching:</p><pre>import { useQuery, useMutation, useQueryClient } from &quot;react-query&quot;;<br><br>// Fetch data with automatic caching<br>const UserProfile = ({ userId }) =&gt; {<br>  const { data, isLoading, error } = useQuery(<br>    [&quot;user&quot;, userId],<br>    () =&gt; fetchUserById(userId),<br>    {<br>      staleTime: 5 * 60 * 1000, // Data considered fresh for 5 minutes<br>      cacheTime: 30 * 60 * 1000, // Cache retained for 30 minutes<br>      refetchOnWindowFocus: false, // Don&#39;t refetch when tab regains focus<br>    },<br>  );<br><br>  if (isLoading) return &lt;Spinner /&gt;;<br>  if (error) return &lt;ErrorMessage error={error} /&gt;;<br><br>  return &lt;UserProfileContent user={data} /&gt;;<br>};</pre><h3>Advanced Caching Strategies</h3><p>React Query enables sophisticated caching patterns:</p><pre>// Optimistic updates<br>const TodoList = () =&gt; {<br>  const queryClient = useQueryClient();<br>  const { data: todos } = useQuery(&quot;todos&quot;, fetchTodos);<br><br>  const mutation = useMutation((newTodo) =&gt; createTodo(newTodo), {<br>    // Optimistically update the UI<br>    onMutate: async (newTodo) =&gt; {<br>      // Cancel any outgoing refetches<br>      await queryClient.cancelQueries(&quot;todos&quot;);<br><br>      // Snapshot the previous value<br>      const previousTodos = queryClient.getQueryData(&quot;todos&quot;);<br><br>      // Optimistically update to the new value<br>      queryClient.setQueryData(&quot;todos&quot;, (old) =&gt; [<br>        ...old,<br>        { ...newTodo, id: Date.now() },<br>      ]);<br><br>      // Return a context with the previous value<br>      return { previousTodos };<br>    },<br>    // If the mutation fails, use the context we returned above<br>    onError: (err, newTodo, context) =&gt; {<br>      queryClient.setQueryData(&quot;todos&quot;, context.previousTodos);<br>    },<br>    // Always refetch after error or success<br>    onSettled: () =&gt; {<br>      queryClient.invalidateQueries(&quot;todos&quot;);<br>    },<br>  });<br><br>  return (<br>    &lt;div&gt;<br>      &lt;TodoForm onSubmit={(todo) =&gt; mutation.mutate(todo)} /&gt;<br>      &lt;TodoItems items={todos} /&gt;<br>    &lt;/div&gt;<br>  );<br>};</pre><p>The benefits of this approach include:</p><ul><li>Instant UI updates for better user experience</li><li>Automatic background refetching to ensure data consistency</li><li>Graceful error handling with automatic rollback</li><li>Reduced server load by minimizing unnecessary requests</li></ul><h3>Prefetching and Background Updates</h3><p>React Query allows prefetching data before it’s needed:</p><pre>const App = () =&gt; {<br>  const queryClient = useQueryClient();<br><br>  // Prefetch user data when the app loads<br>  useEffect(() =&gt; {<br>    queryClient.prefetchQuery([&quot;user&quot;, &quot;current&quot;], fetchCurrentUser);<br>  }, [queryClient]);<br><br>  return (<br>    &lt;Router&gt;<br>      &lt;Routes&gt;<br>        &lt;Route path=&quot;/&quot; element={&lt;Home /&gt;} /&gt;<br>        &lt;Route<br>          path=&quot;/profile&quot;<br>          element={&lt;Profile /&gt;}<br>          onMouseEnter={() =&gt; {<br>            // Prefetch when user hovers over link<br>            queryClient.prefetchQuery([&quot;userSettings&quot;], fetchUserSettings);<br>          }}<br>        /&gt;<br>      &lt;/Routes&gt;<br>    &lt;/Router&gt;<br>  );<br>};</pre><p>Prefetching strategies can dramatically improve perceived performance by loading data before the user explicitly requests it. This works especially well for:</p><ul><li>Navigation paths that users are likely to follow</li><li>Data that’s frequently accessed across different parts of the application</li><li>Resources that are slow to load but critical for functionality</li></ul><p>By strategically prefetching and caching data, you can create applications that feel instantaneous to users while minimizing server load and network traffic.</p><h3>7. Debouncing and Throttling</h3><p>Controlling high-frequency events is essential for smooth user experiences. Debouncing and throttling are two techniques that can significantly improve performance when dealing with rapidly firing events.</p><h3>Debouncing</h3><p>Debouncing ensures that a function is not invoked until a certain amount of time has passed since the last call, which is particularly useful in scenarios like search inputs, where you want to wait until the user stops typing before making an API call. Here’s how you can implement debouncing with a 300ms delay:</p><pre>import { useState, useCallback } from &quot;react&quot;;<br>import { debounce } from &quot;lodash&quot;;<br><br>const SearchComponent = () =&gt; {<br>  const [searchTerm, setSearchTerm] = useState(&quot;&quot;);<br>  const [results, setResults] = useState([]);<br><br>  const debouncedSearch = useCallback(<br>    debounce(async (term) =&gt; {<br>      const response = await fetchSearchResults(term);<br>      setResults(response.data);<br>    }, 300),<br>    [],<br>  );<br><br>  const handleChange = (e) =&gt; {<br>    setSearchTerm(e.target.value);<br>    debouncedSearch(e.target.value);<br>  };<br><br>  return (<br>    &lt;div&gt;<br>      &lt;input<br>        type=&quot;text&quot;<br>        value={searchTerm}<br>        onChange={handleChange}<br>        placeholder=&quot;Search...&quot;<br>      /&gt;<br>      &lt;SearchResults results={results} /&gt;<br>    &lt;/div&gt;<br>  );<br>};</pre><p>In this implementation, we use debounce to ensure the search function is only called 300ms after the user stops typing. If the user types quickly, the previous calls are canceled, and only the last call is executed, preventing unnecessary API requests.</p><p>Debouncing is particularly useful for:</p><ul><li>Search inputs, where you want to wait until the user stops typing before sending requests.</li><li>Form validation that should not be triggered on every keystroke.</li><li>Handling resize events or any other event that could fire repeatedly within a short period.</li></ul><h3>Throttling</h3><p>Throttling ensures that a function executes at a fixed interval, regardless of how often it’s triggered. This is particularly useful for events that fire frequently, such as mouse movements, scrolling, or window resizing. By limiting the execution rate of a function, throttling helps reduce unnecessary calculations or re-renders, improving performance.</p><p>For example, when tracking the mouse position on mousemove, the event fires many times per second. By using throttling, we ensure that the function runs only once every 200 milliseconds, preventing excessive updates while still providing near-real-time feedback.</p><pre>import { useState, useRef, useCallback } from &quot;react&quot;;<br>import { throttle } from &quot;lodash&quot;;<br><br>const MouseTracker = () =&gt; {<br>  const [mousePosition, setMousePosition] = useState({ x: 0, y: 0 });<br>  const containerRef = useRef(null);<br><br>  const handleMouseMove = useCallback(<br>    throttle((event) =&gt; {<br>      setMousePosition({ x: event.clientX, y: event.clientY });<br>    }, 200),<br>    [],<br>  );<br><br>  return (<br>    &lt;div<br>      ref={containerRef}<br>      className=&quot;mouse-tracker&quot;<br>      onMouseMove={handleMouseMove}<br>      style={{ height: &quot;100vh&quot;, border: &quot;1px solid black&quot; }}<br>    &gt;<br>      &lt;p&gt;<br>        Mouse Position: X: {mousePosition.x}, Y: {mousePosition.y}<br>      &lt;/p&gt;<br>    &lt;/div&gt;<br>  );<br>};</pre><p>Throttling is ideal for:</p><ul><li>Scroll events that trigger animations or calculations</li><li>Mousemove events for drag-and-drop or hover effects</li><li>Window resize handlers that update layouts</li><li>Tracking user activity at regular intervals</li></ul><h3>8. Suspense for Data Fetching</h3><p>React Suspense provides a powerful way to handle asynchronous data fetching while improving perceived performance and user experience. Instead of manually tracking loading states, Suspense allows you to declaratively define fallbacks for your components.</p><p>When paired with a data-fetching library like React Query, Suspense makes handling asynchronous operations cleaner and more efficient.</p><pre>import { Suspense } from &quot;react&quot;;<br>import { useQuery } from &quot;@tanstack/react-query&quot;;<br><br>const fetchUser = async () =&gt; {<br>  const res = await fetch(&quot;/api/user&quot;);<br>  return res.json();<br>};<br><br>const UserProfile = () =&gt; {<br>  const { data } = useQuery({ queryKey: [&quot;user&quot;], queryFn: fetchUser });<br><br>  return &lt;div&gt;User: {data.name}&lt;/div&gt;;<br>};<br><br>const App = () =&gt; (<br>  &lt;Suspense fallback={&lt;div&gt;Loading user...&lt;/div&gt;}&gt;<br>    &lt;UserProfile /&gt;<br>  &lt;/Suspense&gt;<br>);</pre><p>React Suspense simplifies state management by removing the need to manually track loading states. It enhances the loading experience by displaying a fallback UI while data is being fetched, preventing flickering and layout shifts caused by conditional rendering. Additionally, it helps improve perceived performance by ensuring that components load seamlessly without jarring transitions.</p><p>Beyond performance, Suspense also improves code organization by keeping components focused on rendering logic rather than handling async states. This makes applications easier to maintain and scale. It is particularly useful when dealing with large datasets, streaming data, or preloading resources for a smoother user experience. As React continues to evolve, Suspense is set to become an essential tool for managing asynchronous operations efficiently.</p><h3>Conclusion</h3><p>Optimizing React applications requires a multi-faceted approach, addressing everything from data structures to rendering strategies. The techniques covered in this guide provide a comprehensive toolkit for improving your application’s performance:</p><ol><li><strong>Smart Data Manipulation</strong>: Choose the right data structures and operation order to minimize processing time.</li><li><strong>Strategic Rendering</strong>: Create component boundaries and preserve references to prevent unnecessary re-renders.</li><li><strong>Advanced Memoization</strong>: Use React’s optimization hooks strategically to avoid redundant calculations.</li><li><strong>Function and Event Optimization</strong>: Define functions efficiently and use event delegation to reduce overhead.</li><li><strong>Component Virtualization</strong>: Render only what’s visible to handle large datasets efficiently.</li><li><strong>Data Fetching and Caching</strong>: Implement effective caching strategies with React Query to minimize network requests.</li><li><strong>Debouncing and Throttling</strong>: Control high-frequency events to maintain smooth user experiences.</li><li><strong>Suspense for Data Fetching</strong>: Use React’s Suspense API to manage asynchronous data loading seamlessly.</li></ol><p>By applying these techniques selectively and measuring their impact, you can create React applications that remain responsive even as they grow in complexity. Remember that performance optimization is an iterative process — always measure before and after your changes to ensure they’re having the desired effect.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3d21f85b612" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Virtualizing React]]></title>
            <link>https://medium.com/@renanleonel/virtualizing-react-f26361d5960b?source=rss-76d2ceb73f6c------2</link>
            <guid isPermaLink="false">https://medium.com/p/f26361d5960b</guid>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[virtualization]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Renan Leonel]]></dc:creator>
            <pubDate>Wed, 05 Mar 2025 03:05:43 GMT</pubDate>
            <atom:updated>2025-03-05T03:05:43.782Z</atom:updated>
            <content:encoded><![CDATA[<p>Rendering large lists efficiently in React can be challenging. When dealing with hundreds or thousands of items, the browser’s performance can suffer significantly. This guide explores two powerful approaches to solve this problem through virtualization: a pure implementation built from scratch and a solution using TanStack Virtual. By the end, you’ll understand not only how virtualization works under the hood but also when to choose each approach for your specific needs.</p><p>We’ll explore:</p><ol><li><a href="https://dev.to/rnnlnl/virtualizing-react-20fb#understanding-virtualization"><strong>Understanding Virtualization</strong></a>: What virtualization is and why it’s important</li><li><a href="https://dev.to/rnnlnl/virtualizing-react-20fb#pure-implementation"><strong>Pure Implementation</strong></a>: Step-by-step guide to implement virtualization from scratch</li><li><a href="https://dev.to/rnnlnl/virtualizing-react-20fb#tanstack-virtual-implementation"><strong>TanStack Virtual Implementation</strong></a>: Using a battle-tested library for virtualization</li><li><a href="https://dev.to/rnnlnl/virtualizing-react-20fb#comparing-approaches"><strong>Comparing Approaches</strong></a>: When to use each approach</li></ol><h3>Understanding Virtualization</h3><p>Virtualization is a technique that renders only the visible portion of a large list of items. Instead of rendering all items at once, it maintains a “window” of visible elements that moves as the user scrolls, significantly reducing the number of DOM elements present at any given time.</p><p>To understand how virtualization works, let’s break down its four key components using a simple analogy:</p><ol><li><strong>Virtual Window</strong></li></ol><ul><li>Imagine reading a 500-page book through a small window that shows only 20 pages at once</li><li>Just like you can only see these 20 pages, the DOM only renders the visible items</li><li>As you slide the window up or down the book, new pages come into view while others hide</li><li>In our select component, instead of rendering all 500 items, we show only what fits in view</li></ul><p><strong>2. Buffer Zones</strong></p><ul><li>Like keeping your thumb a few pages ahead and behind where you’re reading</li><li>We keep 10 extra items rendered above and 10 below the visible area</li><li>This preparation ensures smooth transitions, just like having your thumb ready to flip the page</li><li>Example: While 20 items are visible, we actually render 40 (20 visible + 20 buffer)</li></ul><p><strong>3. Height Calculation</strong></p><ul><li>Similar to keeping the book’s full thickness even though you’re only viewing a small section</li><li>We maintain the full scroll height (500 items × 32px) using an invisible element</li><li>This preserves the natural feel of scrolling through a long list</li><li>Example: A 16,000px tall container represents our full 500-item list</li></ul><p><strong>4. Position Management</strong></p><ul><li>Like numbering each page and knowing exactly where to slide the window</li><li>Each item’s position is precisely calculated based on its index</li><li>If you’re at item #100, we position it at exactly 3,200px from the top</li><li>This creates the illusion of a complete list while managing only a few elements</li></ul><p>This approach offers several key benefits:</p><ul><li><strong>Memory Efficiency</strong>: Instead of managing thousands of DOM nodes, the browser only needs to handle a few dozen</li><li><strong>CPU Performance</strong>: Less DOM manipulation means reduced CPU usage during scrolling</li><li><strong>Smooth Scrolling</strong>: With fewer elements to process, the browser can maintain 60fps even during rapid scrolling</li><li><strong>Initial Load Speed</strong>: Applications load faster since they don’t need to create all DOM nodes upfront</li><li><strong>Battery Life</strong>: Reduced processing requirements lead to better battery life on mobile devices</li></ul><p>Understanding these mechanics is crucial for implementing virtualization effectively, whether you’re building it from scratch or using a library like TanStack Virtual.</p><h3>Pure Implementation</h3><p>Let’s start with implementing virtualization from scratch. This approach gives us complete control over the implementation and helps understand the core concepts.</p><p>First, we’ll define our constants:</p><pre>const ITEM_HEIGHT = 32; // Height of each item in pixels<br>const BUFFER_ITEMS = 20; // Number of items to render above/below viewport<br>const TOTAL_ITEMS = 500; // Total number of items in the list<br>const VIEWPORT_HEIGHT = 300; // Height of the visible area</pre><p>The core logic involves three main parts:</p><ol><li><strong>Scroll Position Tracking</strong>: Monitor the scroll position to determine which items should be visible</li><li><strong>Visible Items Calculation</strong>: Calculate the start and end indices of visible items</li><li><strong>Rendering</strong>: Position the visible items correctly within the viewport</li></ol><p>Here’s the implementation:</p><pre>export const Pure = () =&gt; {<br>  const [scrollTop, setScrollTop] = useState(0);<br>  const containerRef = useRef&lt;HTMLDivElement&gt;(null);<br><br>  // Calculate which items should be visible<br>  const startIndex = Math.max(<br>    0,<br>    Math.floor(scrollTop / ITEM_HEIGHT) - BUFFER_ITEMS<br>  );<br><br>  const endIndex = Math.min(<br>    ALL_ITEMS.length,<br>    Math.ceil((scrollTop + VIEWPORT_HEIGHT) / ITEM_HEIGHT) + BUFFER_ITEMS<br>  );<br><br>  const visibleItems = ALL_ITEMS.slice(startIndex, endIndex);<br><br>  return (<br>    &lt;Select&gt;<br>      &lt;SelectContent&gt;<br>        &lt;div<br>          ref={containerRef}<br>          onScroll={handleScroll}<br>          style={{ height: VIEWPORT_HEIGHT }}<br>          className=&#39;relative overflow-auto&#39;<br>        &gt;<br>          {/* Total height placeholder */}<br>          &lt;div<br>            className=&#39;absolute top-0 left-0 w-full&#39;<br>            style={{ height: ALL_ITEMS.length * ITEM_HEIGHT }}<br>          /&gt;<br><br>          {/* Rendered items */}<br>          &lt;div<br>            className=&#39;absolute right-0 left-0&#39;<br>            style={{ top: startIndex * ITEM_HEIGHT }}<br>          &gt;<br>            {visibleItems.map((item) =&gt; (<br>              &lt;SelectItem key={item.value} value={item.value}&gt;<br>                {item.label}<br>              &lt;/SelectItem&gt;<br>            ))}<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      &lt;/SelectContent&gt;<br>    &lt;/Select&gt;<br>  );<br>};</pre><p>Let’s break down the implementation to understand how each piece works together:</p><ol><li><strong>Container Setup</strong></li></ol><pre>&lt;div<br>  ref={containerRef}<br>  onScroll={handleScroll}<br>  style={{ height: VIEWPORT_HEIGHT }}<br>  className=&#39;relative overflow-auto&#39;<br>&gt;</pre><p>This is our viewport container. It has a fixed height (VIEWPORT_HEIGHT = 300px) and enables scrolling. Think of it as the &quot;window&quot; through which we view our items.</p><p>2. <strong>Visible Items Container</strong></p><pre>&lt;div<br>  className=&#39;absolute right-0 left-0&#39;<br>  style={{ top: startIndex * ITEM_HEIGHT }}<br>&gt;<br>  {visibleItems.map((item) =&gt; (<br>    &lt;SelectItem key={item.value} value={item.value}&gt;<br>      {item.label}<br>    &lt;/SelectItem&gt;<br>  ))}<br>&lt;/div&gt;</pre><p>This container holds only the currently visible items. Its position is dynamically calculated based on scroll position:</p><ul><li>If you’re scrolled to item #50, startIndex = 50</li><li>The container is positioned at top: 50 * 32px = 1600px</li><li>Only items 50–70 (plus buffer) are actually rendered</li></ul><p><strong>3. Scroll Position Tracking</strong></p><pre>const startIndex = Math.max(<br>  0,<br>  Math.floor(scrollTop / ITEM_HEIGHT) - BUFFER_ITEMS,<br>);<br><br>const endIndex = Math.min(<br>  ALL_ITEMS.length,<br>  Math.ceil((scrollTop + VIEWPORT_HEIGHT) / ITEM_HEIGHT) + BUFFER_ITEMS,<br>);</pre><p>This calculation determines which items should be rendered:</p><ul><li>scrollTop tells us how far we&#39;ve scrolled</li><li>We divide by ITEM_HEIGHT to get the first visible item</li><li>We add BUFFER_ITEMS (20) above and below for smooth scrolling</li><li>Math.max and Math.min ensure we stay within list bounds</li></ul><p>The magic happens when scrolling:</p><ol><li>User scrolls → scrollTop changes</li><li>New startIndex and endIndex are calculated</li><li>visibleItems array updates with new slice of items</li><li>Visible items container repositions using top style</li><li>Only ~60 items exist in DOM at any time (20 visible + 40 buffer)</li></ol><p>This creates the illusion of scrolling through thousands of items while maintaining excellent performance.</p><h3>TanStack Virtual Implementation</h3><p>TanStack Virtual provides a more abstracted approach with additional features and optimizations out of the box. Here’s how to implement the same functionality:</p><pre>export const TanStack = () =&gt; {<br>  const parentRef = useRef&lt;HTMLDivElement&gt;(null);<br><br>  const virtualizer = useVirtualizer({<br>    count: TOTAL_ITEMS,<br>    getScrollElement: () =&gt; parentRef.current,<br>    estimateSize: () =&gt; ITEM_HEIGHT,<br>    overscan: BUFFER_ITEMS,<br>  });<br><br>  return (<br>    &lt;Select&gt;<br>      &lt;SelectContent&gt;<br>        &lt;div<br>          ref={parentRef}<br>          className=&#39;relative overflow-auto&#39;<br>          style={{ height: VIEWPORT_HEIGHT }}<br>        &gt;<br>          &lt;div<br>            className=&#39;relative w-full&#39;<br>            style={{ height: `${virtualizer.getTotalSize()}px` }}<br>          &gt;<br>            {virtualizer.getVirtualItems().map((virtualItem) =&gt; {<br>              const item = ALL_ITEMS[virtualItem.index];<br><br>              return (<br>                &lt;SelectItem<br>                  key={item.value}<br>                  value={item.value}<br>                  className=&#39;absolute left-0 w-full&#39;<br>                  style={{<br>                    height: `${ITEM_HEIGHT}px`,<br>                    transform: `translateY(${virtualItem.start}px)`,<br>                  }}<br>                &gt;<br>                  {item.label}<br>                &lt;/SelectItem&gt;<br>              );<br>            })}<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      &lt;/SelectContent&gt;<br>    &lt;/Select&gt;<br>  );<br>};</pre><h3>Comparing Approaches</h3><p>Now that we’ve explored both implementations, let’s analyze their strengths and use cases. While both solutions effectively handle virtualization, they serve different needs and come with distinct trade-offs. Understanding these differences will help you choose the right approach for your specific requirements.</p><h4>Pure Implementation</h4><ol><li><strong>When to Use:</strong></li></ol><p>a. Learning virtualization concepts</p><p>b. Simple lists with fixed-height items</p><p>c. Projects where bundle size is critical</p><p>d. Need for minimal dependencies</p><p><strong>2. Key Benefits:</strong></p><p>a. Full control over implementation</p><p>b. Zero external dependencies</p><p>c. Smaller bundle size</p><p>d. Great for understanding core concepts</p><h4>TanStack Virtual</h4><ol><li><strong>When to Use:</strong></li></ol><p>a. Production applications</p><p>b. Complex virtualization needs</p><p>c. Dynamic height items</p><p>d. Need for advanced features</p><p><strong>2. Key Benefits:</strong></p><p>a. Production-ready with edge case handling</p><p>b. Dynamic size support</p><p>c. Built-in optimizations</p><p>d. TypeScript support</p><p>e. Active maintenance</p><h3>Try It Yourself!</h3><p>To fully appreciate the impact of virtualization, I encourage you to clone the <a href="https://github.com/renanleonel/react-virtualization">demo repository</a> and experiment with different list sizes. Try setting TOTAL_ITEMS to values like 1,000, 2,000, and even 10,000. Open your browser&#39;s DevTools (F12) and inspect the DOM elements for both implementations:</p><ul><li>In the non-virtualized version, you’ll see thousands of &lt;SelectItem&gt; elements being rendered at once, causing significant performance issues and potential browser freezing when the select is opened.</li><li>In contrast, both virtualized implementations (Pure and TanStack) maintain only about 60 DOM elements at any time (visible items + buffer), regardless of the total list size. You can verify this by inspecting the DOM as you scroll — elements are dynamically added and removed to maintain optimal performance.</li></ul><p>This hands-on comparison clearly demonstrates why virtualization is crucial for handling large datasets in web applications.</p><h3>Conclusion</h3><p>Virtualization significantly improves application performance by rendering only what users see. We explored two ways to achieve this:</p><ul><li>A <strong>pure implementation</strong> that gives you complete control and understanding of the virtualization process</li><li><strong>TanStack Virtual</strong> that provides a production-ready solution with advanced features out of the box</li></ul><p>Both approaches effectively solve the same problem: handling large lists efficiently. Choose the one that best fits your needs — whether it’s learning the concepts, having full control, or quickly implementing a robust solution.</p><h3>Resources</h3><ul><li><a href="https://github.com/renanleonel/react-virtualization">Demo Repository</a></li><li><a href="https://tanstack.com/virtual/latest">TanStack Virtual Documentation</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f26361d5960b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dockerizing Next.js]]></title>
            <link>https://medium.com/@renanleonel/dockerizing-next-js-a3d9c51c0182?source=rss-76d2ceb73f6c------2</link>
            <guid isPermaLink="false">https://medium.com/p/a3d9c51c0182</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[docker-compose]]></category>
            <category><![CDATA[containerization]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[containers]]></category>
            <dc:creator><![CDATA[Renan Leonel]]></dc:creator>
            <pubDate>Sat, 20 Apr 2024 21:02:41 GMT</pubDate>
            <atom:updated>2024-04-20T21:03:15.871Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gbl1WeVW4Rk_z2sJssC-Vw.png" /></figure><p>This tutorial will cover the step-by-step process of containerizing a Next.js application using Docker. We will follow these steps:</p><ol><li><strong>Installing Necessary Tools</strong>: For this tutorial, we will need WSL, Docker, Docker Compose, and a Next.js project.</li><li><strong>Dockerfile</strong>: We will create two Dockerfiles, one for the development environment and the other for the production environment.</li><li><strong>Docker Compose</strong>: We will create a Docker Compose file to manage Docker containers.</li><li><strong>Publishing to Docker Hub</strong>: We will publish the image to Docker Hub to make it available for others to use.</li><li><strong>Docker Cheat Sheet</strong>: A list of useful commands for managing Docker containers.</li></ol><h3>Installing Necessary Tools</h3><p>This tutorial assumes that you’re using Windows as your operating system. If you’re using a different operating system, the commands may vary.</p><p>Firstly, we need to install WSL (Windows Subsystem for Linux), which is a feature of Windows that allows you to run a Linux environment directly on your Windows computer without the need for a virtual machine. To do this, open PowerShell as an administrator and execute the following command:</p><pre>wsl --install</pre><p>If you encounter any issues during installation, you can refer to the official tutorial for WSL installation provided by Microsoft <a href="https://docs.microsoft.com/en-us/windows/wsl/install">here</a>.</p><p>Now, we can proceed to install Docker and Docker Compose.</p><p>Docker is a virtualization platform that encapsulates applications in isolated containers, providing consistency and efficiency in development. This allows the application to run autonomously and consistently in any environment, eliminating conflicts between different software versions.</p><p>For installation, follow the comprehensive tutorials created by Digital Ocean for Docker <a href="https://www.digitalocean.com/community/tutorials/how-to-install-and-use-docker-on-ubuntu-22-04">here</a> and Docker Compose <a href="https://www.digitalocean.com/community/tutorials/how-to-install-and-use-docker-compose-on-ubuntu-22-04">here</a> on Ubuntu.</p><p>Finally, create a Next.js application using the command: npx create-next-app@latest or use an existing project. For this tutorial, we will use <a href="https://github.com/renanleonel/nextjs-template">this template repository</a> that I use for all my projects, using pnpm as the package manager.</p><h3>Dockerfile</h3><p>The Dockerfile is a configuration file that contains all the necessary commands to build an image. For this tutorial, we will create two files: one for the development environment and another for the production environment.</p><p>First, create a `Dockerfile.prod` file in the root directory of your project. Then, add the following code:</p><pre>FROM node:20 AS base<br>WORKDIR /app<br>RUN npm i -g pnpm<br>COPY package.json pnpm-lock.yaml ./<br><br>RUN pnpm install<br><br>COPY . .<br>RUN pnpm build<br><br>FROM node:20-alpine3.19 as release<br>WORKDIR /app<br>RUN npm i -g pnpm<br><br>COPY --from=base /app/node_modules ./node_modules<br>COPY --from=base /app/package.json ./package.json<br>COPY --from=base /app/.next ./.next<br><br>EXPOSE 3000<br><br>CMD [&quot;pnpm&quot;, &quot;start&quot;]</pre><p>Now, let’s analyze the commands in the `Dockerfile.prod` file:</p><pre># Define the base image as node:20 and name it as base.<br>FROM node:20 AS base<br><br># Set the working directory inside the container to /app.<br># We need to set the working directory so Docker knows where to run the commands.<br>WORKDIR /app<br><br># Globally install the package manager pnpm.<br>RUN npm i -g pnpm<br><br># Copy the package.json and pnpm-lock.yaml files to the working directory in the container.<br># This command is necessary for Docker to install project dependencies.<br>COPY package.json pnpm-lock.yaml ./<br><br># Install project dependencies using pnpm.<br>RUN pnpm install<br><br># Copy all files from the context directory (where the Dockerfile is located) to the working directory in the container.<br>COPY . .<br><br># Run the project build command using pnpm.<br>RUN pnpm build<br><br># Define a second stage of the image based on node:20-alpine3.19 and name it as release.<br># Alpine image is a lighter version of node, which helps reduce the final image size.<br>FROM node:20-alpine3.19 as release<br><br># Set the working directory inside the container to /app.<br>WORKDIR /app<br><br># Globally install the package manager pnpm.<br>RUN npm i -g pnpm<br><br># Copy the node_modules folder from the base stage to the node_modules directory in the release stage.<br>COPY --from=base /app/node_modules ./node_modules<br><br># Copy the package.json file from the base stage to the current directory in the release stage.<br>COPY --from=base /app/package.json ./package.json<br><br># Copy the .next folder from the base stage to the .next directory in the release stage.<br>COPY --from=base /app/.next ./.next<br><br><br># Define the default command to be executed when the container is started with pnpm start.<br>CMD [&quot;pnpm&quot;, &quot;start&quot;]</pre><p>Next, create a `Dockerfile.dev` file in the root of your project.</p><pre>FROM node:20 AS base<br>WORKDIR /app<br>RUN npm i -g pnpm<br>COPY package.json pnpm-lock.yaml ./<br><br>RUN pnpm install<br><br>COPY . .<br><br>FROM node:20-alpine3.19 as release<br>WORKDIR /app<br>RUN npm i -g pnpm<br><br>COPY --from=base /app/node_modules ./node_modules<br>COPY --from=base /app/package.json ./package.json<br>COPY --from=base /app/.next ./.next<br>COPY --from=base /app/src ./src<br>COPY --from=base /app .<br><br>EXPOSE 3000<br><br>CMD [&quot;pnpm&quot;, &quot;dev&quot;]</pre><p>We can test if the Dockerfile is working correctly by building our application using the command:</p><pre>docker build -t nextjs:v1 -f Dockerfile.prod .</pre><p>It’s worth highlighting the meaning of the flags used:</p><p>- `-t`: This flag is used to tag an image.</p><p>- `-f`: This flag specifies the Dockerfile to use for building an image.</p><p>- `-p`: This flag maps ports between the Docker container and the host system.</p><p>Upon accessing <a href="http://localhost:3000,">http://localhost:3000,</a> you should see the Next.js application running inside a Docker container. You can also verify if the container is running correctly by executing the command:</p><pre>docker ps</pre><p>If everything is working correctly, you should see something like this:</p><pre>CONTAINER ID   IMAGE        COMMAND                  CREATED         STATUS         PORTS                                       NAMES<br>88c1975e087b   nextjs:v1   &quot;docker-entrypoint.s…&quot;   7 seconds ago   Up 6 seconds   0.0.0.0:3000-&gt;3000/tcp, :::3000-&gt;3000/tcp   festive_leavitt</pre><p>However, hot reload isn’t working when using the `Dockerfile.dev` because the container is not watching for changes in the files.</p><p>Furthermore, manually executing these commands every time we want to run the application is a tedious process. To address these issues, let’s use Docker Compose.</p><h3>Docker Compose</h3><p>Docker Compose is a tool that simplifies the management of multiple Docker containers, allowing you to define and run them all with a single command, simplifying the configuration and management of multi-container applications.</p><p>Additionally, we have access to the concept of volumes, which allow data persistence between containers and the host, ensuring that data is not lost when containers are restarted or removed and allowing changes in files to be reflected in the container in real-time. Furthermore, Docker Compose allows the definition of environment variables in a `.env` file to facilitate the configuration of the application.</p><p>To use Docker Compose, we need to create a configuration file called `docker-compose.yml`. This file defines the services that will be run by Docker Compose, as well as the configurations for each service.</p><pre>version: &quot;3.7&quot;<br><br>services:<br>  dev:<br>    build:<br>      context: .<br>      dockerfile: Dockerfile.dev<br>    container_name: demo-docker-nextjs-dev<br>    environment:<br>      - WATCHPACK_POLLING=true<br>    volumes:<br>      - .:/app<br>      - /app/node_modules<br>      - /app/.next<br>    ports:<br>      - &quot;3000:3000&quot;<br>    env_file:<br>      - .env.local<br>  prod:<br>    build:<br>      context: .<br>      dockerfile: Dockerfile.prod<br>    container_name: demo-docker-nextjs<br>    ports:<br>      - &quot;3000:3000&quot;<br>    env_file:<br>      - .env.local<br><br>volumes:<br>  node_modules:</pre><p>Let’s analyze the commands in the `docker-compose.yml` file:</p><pre># Define the version of Docker Compose.<br>version: &quot;3.7&quot;<br><br># Define the services to be run by Docker Compose.<br>services:<br>  # Define the dev service.<br>  # This service will be used to run the application in the development environment.<br>  dev:<br>    # Define the build context as the current directory and the Dockerfile to be used as Dockerfile.dev.<br>    build:<br>      context: .<br>      dockerfile: Dockerfile.dev<br>    # Define the container name.<br>    container_name: demo-docker-nextjs-dev<br>    # Define the environment variable WATCHPACK_POLLING as true. This is necessary for hot reload to work correctly.<br>    environment:<br>      - WATCHPACK_POLLING=true<br>    # Define the volumes to be mounted in the container.<br>    # The volume .:/app maps the current working directory to the /app directory in the container.<br>    # The volume /app/node_modules is used to persist project dependencies between containers.<br>    # The volume /app/.next is used to persist files generated by Next.js between containers.<br>    volumes:<br>      - .:/app<br>      - /app/node_modules<br>      - /app/.next<br>    # Maps the ports to be exposed on the host.<br>    ports:<br>      - &quot;3000:3000&quot;<br>    # Define the environment file to be used.<br>    env_file:<br>      - .env.local<br>  # Define the prod service.<br>  # This service will be used to run the application in the production environment.<br>  prod:<br>    # Define the build context as the current directory and the Dockerfile to be used as Dockerfile.prod.<br>    build:<br>      context: .<br>      dockerfile: Dockerfile.prod<br>    # Define the container name.<br>    container_name: demo-docker-nextjs<br>    # Maps the ports to be exposed on the host.<br>    ports:<br>      - &quot;3000:3000&quot;<br>    # Define the environment file to be used.<br>    env_file:<br>      - .env.local<br><br># Define the volumes to be used.<br># The node_modules volume is used to persist project dependencies between containers.<br>volumes:<br>  node_modules:</pre><p>To run the application using Docker Compose, execute the command:</p><pre>docker-compose up prod</pre><p>Now, upon accessing `http://localhost:3000`, you should see the Next.js application running inside a Docker container with hot reload functioning in the development environment. Try making a change to any file and observe the changes being reflected in the container in real-time.</p><h3>Publishing to Docker Hub</h3><p>Finally, we can upload our application to <a href="https://hub.docker.com/">Docker Hub</a> so that other people can use the image we created. To do this, follow the steps below:</p><p>1. Log in to Docker Hub using the command:</p><pre>docker login</pre><p>2. Build the image using the command:</p><pre>docker build -t &lt;DOCKERHUB_USERNAME&gt;/&lt;REPOSITORY&gt;:&lt;TAG&gt; -f &lt;DOCKERFILE&gt; .</pre><p>3. Push the image to Docker Hub using the command:</p><pre>docker push &lt;DOCKERHUB_USERNAME&gt;/&lt;REPOSITORY&gt;:&lt;TAG&gt;</pre><p>We can view the image through the link on Docker Hub <a href="https://hub.docker.com/r/renanleonel/demo-docker-nextjs-prod">here</a>. To run the image in any environment that supports Docker, we should download the image using the command:</p><pre>docker push renanleonel/demo-docker-nextjs-prod:v1</pre><p>and then run the container:</p><pre>docker run -p 3000:3000 renanleonel/demo-docker-nextjs-prod:v1</pre><p>Now your Next.js application is containerized and ready to be used in any environment that supports Docker.</p><h3>Docker Cheat Sheet</h3><p>Here are some useful commands for managing Docker containers:</p><p>- View all running containers</p><pre>docker ps -a</pre><p>- To stop a container, execute the command</p><pre>docker stop &lt;CONTAINER ID&gt;</pre><p>- Stop all running Docker containers</p><pre>docker stop $(docker ps -a -q)</pre><p>- To remove a container, execute the command</p><pre>docker rm &lt;CONTAINER ID&gt;</pre><p>- Remove all Docker containers</p><pre>docker rm $(docker ps -a -q)</pre><p>- Remove all stopped Docker containers</p><pre>docker container prune</pre><p>- To view the images on your system, execute the command</p><pre>docker image ls</pre><p>- To remove an image, execute the command</p><pre>docker image rm &lt;REPOSITORY&gt;:&lt;TAG&gt;</pre><p>-If the image is being used by a container, you must stop and remove the container before removing the image. Another way is to add the -f flag to force removal.</p><pre>docker image rm -f &lt;REPOSITORY&gt;:&lt;TAG&gt;</pre><p>- To remove all images, execute the command</p><pre>docker rmi $(docker images -q)</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a3d9c51c0182" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to set up NextAuth v5 authentication with middleware and Jest configuration in Next.js 14]]></title>
            <link>https://medium.com/@renanleonel/how-to-set-up-nextauth-v5-authentication-with-middleware-and-jest-configuration-in-next-js-14-ca3e64bfb7d5?source=rss-76d2ceb73f6c------2</link>
            <guid isPermaLink="false">https://medium.com/p/ca3e64bfb7d5</guid>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[jest]]></category>
            <category><![CDATA[nextauth]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[Renan Leonel]]></dc:creator>
            <pubDate>Sat, 10 Feb 2024 17:25:21 GMT</pubDate>
            <atom:updated>2024-02-10T17:25:21.040Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2YJ_kIlPMGEPtZ84KhF3Yg.png" /></figure><p>This article aims to demonstrate how to implement an authentication flow with middleware using next-auth v5, while also containing the necessary configs to setup a test environment for next-auth v5 using jest/testing-library, with examples of how to mock a server action and the useFormState hook.</p><p><strong>NOTE: </strong>This repository uses react and react-dom in canary versions (18.3.0-canary)</p><p>This article is divided in two sections:</p><p>1- Next Auth v5 implementation with middleware</p><p>2- Setting a test environment for Next Auth, with server actions and useFormState mock.</p><p>The full code for this implementation can be found here: <a href="https://github.com/renanleonel/next-auth-v5-middleware">https://github.com/renanleonel/next-auth-v5-middleware</a></p><ol><li><strong>Setting up the environment</strong></li></ol><p>First, we need to install the necessary packages.</p><pre>pnpm add next-auth@beta</pre><p>Inside the App folder, create:</p><pre>src/app/api/auth/[...nextauth]/route.ts<br><br>export { GET, POST } from &#39;@/auth&#39;;</pre><p>Inside src folder, create a file called auth.ts, where we are going to create a mock function to simulate the access to the database (getUser). This is the function that will be called whenever the signIn method from NextAuth is called.</p><pre>src/auth.ts<br><br>import NextAuth from &#39;next-auth&#39;;<br>import { authConfig } from &#39;./auth.config&#39;;<br>import Credentials from &#39;next-auth/providers/credentials&#39;;<br><br>async function getUser(email: string, password: string): Promise&lt;any&gt; {<br> return {<br>  id: 1,<br>  name: &#39;test user&#39;,<br>  email: email,<br>  password: password,<br> };<br>}<br><br>export const {<br> auth,<br> signIn,<br> signOut,<br> handlers: { GET, POST },<br>} = NextAuth({<br> ...authConfig,<br> providers: [<br>  Credentials({<br>   name: &#39;credentials&#39;,<br>   credentials: {<br>    email: { label: &#39;email&#39;, type: &#39;text&#39; },<br>    password: { label: &#39;password&#39;, type: &#39;password&#39; },<br>   },<br>   async authorize(credentials) {<br>    const user = await getUser(<br>     credentials.email as string,<br>     credentials.password as string<br>    );<br><br>    return user ?? null;<br>   },<br>  }),<br> ],<br>});</pre><p>Also create auth.config.ts inside src:</p><pre>src/auth.config.ts<br><br>import type { NextAuthConfig } from &#39;next-auth&#39;;<br><br>export const authConfig = {<br> session: {<br>  strategy: &#39;jwt&#39;,<br> },<br> pages: {<br>  error: &#39;/&#39;,<br>  signIn: &#39;/&#39;,<br>  signOut: &#39;/&#39;,<br> },<br> callbacks: {<br>  authorized({ auth }) {<br>   const isAuthenticated = !!auth?.user;<br><br>   return isAuthenticated;<br>  },<br> },<br> providers: [],<br>} satisfies NextAuthConfig;</pre><p>We need to define the routes of our application. I’m going to create two pages, the root page where all users can access, and the /protected page, where only logged users can access.</p><p>First, create a file in src/lib/routes.ts. This constants will be used in the middleware verification.</p><pre>src/lib/routes.ts<br><br>export const ROOT = &#39;/&#39;;<br>export const PUBLIC_ROUTES = [&#39;/&#39;];<br>export const DEFAULT_REDIRECT = &#39;/protected&#39;;</pre><p>Then, create the two pages:</p><pre>src/app/page.tsx<br><br>import Form from &#39;@/components/form&#39;;<br><br>const Root = () =&gt; {<br> return (<br>  &lt;main className=&#39;flex items-center justify-center h-screen w-screen&#39;&gt;<br>   &lt;Form /&gt;<br>  &lt;/main&gt;<br> );<br>};<br><br>export default Root;</pre><pre>src/components/form.tsx<br><br>&#39;use client&#39;;<br><br>import { login } from &#39;@/lib/actions&#39;;<br>import { useFormState } from &#39;react-dom&#39;;<br>import { Input } from &#39;@/components/ui/input&#39;;<br>import { Button } from &#39;@/components/ui/button&#39;;<br><br>const loginInitialState = {<br> message: &#39;&#39;,<br> errors: {<br>  email: &#39;&#39;,<br>  password: &#39;&#39;,<br>  credentials: &#39;&#39;,<br>  unknown: &#39;&#39;,<br> },<br>};<br><br>const Form = () =&gt; {<br> const [formState, formAction] = useFormState(login, loginInitialState);<br><br> return (<br>  &lt;form action={formAction} className=&#39;space-y-4 w-full max-w-sm&#39;&gt;<br>   &lt;Input required name=&#39;email&#39; placeholder=&#39;email&#39; /&gt;<br>   &lt;Input<br>    required<br>    name=&#39;password&#39;<br>    type=&#39;password&#39;<br>    placeholder=&#39;password&#39;<br>   /&gt;<br>   &lt;Button variant=&#39;secondary&#39; className=&#39;w-full&#39; type=&#39;submit&#39;&gt;<br>    submit<br>   &lt;/Button&gt;<br>  &lt;/form&gt;<br> );<br>};<br><br>export default Form;</pre><pre>src/app/protected/page.tsx<br><br>import { auth } from &#39;@/auth&#39;;<br>import { logout } from &#39;@/lib/actions&#39;;<br>import { Button } from &#39;@/components/ui/button&#39;;<br><br>const Protected = async () =&gt; {<br> const session = await auth();<br><br> session?.user?.email;<br><br> return (<br>  &lt;form<br>   action={logout}<br>   className=&#39;h-screen w-screen flex flex-col justify-center items-center gap-10&#39;<br>  &gt;<br>   &lt;div&gt;<br>    &lt;p className=&#39;text-white&#39;&gt;{session?.user?.name}&lt;/p&gt;<br>    &lt;p className=&#39;text-white&#39;&gt;{session?.user?.email}&lt;/p&gt;<br>   &lt;/div&gt;<br>   &lt;Button type=&#39;submit&#39; className=&#39;w-40&#39; variant=&#39;secondary&#39;&gt;<br>    logout<br>   &lt;/Button&gt;<br>  &lt;/form&gt;<br> );<br>};<br><br>export default Protected;</pre><p>We are using zod to do a schema validation for our forms:</p><pre>src/types/schema.ts<br><br>import { z } from &#39;zod&#39;;<br><br>export const loginSchema = z.object({<br> email: z<br>  .string()<br>  .trim()<br>  .min(1, { message: &#39;Email required!&#39; })<br>  .email({ message: &#39;Invalid email!&#39; }),<br> password: z<br>  .string()<br>  .trim()<br>  .min(1, { message: &#39;Password required!&#39; })<br>  .min(8, { message: &#39;Password must have at least 8 characters!&#39; }),<br>});</pre><p>Create a file called actions.ts to create our login action:</p><pre>src/lib/actions.ts<br><br>&#39;use server&#39;;<br><br>import { AuthError } from &#39;next-auth&#39;;<br>import { signIn, signOut } from &#39;@/auth&#39;;<br>import { loginSchema } from &#39;@/types/schema&#39;;<br><br>const defaultValues = {<br> email: &#39;&#39;,<br> password: &#39;&#39;,<br>};<br><br>export async function login(prevState: any, formData: FormData) {<br> try {<br>  const email = formData.get(&#39;email&#39;);<br>  const password = formData.get(&#39;password&#39;);<br><br>  const validatedFields = loginSchema.safeParse({<br>   email: email,<br>   password: password,<br>  });<br><br>  if (!validatedFields.success) {<br>   return {<br>    message: &#39;validation error&#39;,<br>    errors: validatedFields.error.flatten().fieldErrors,<br>   };<br>  }<br><br>  await signIn(&#39;credentials&#39;, formData);<br><br>  return {<br>   message: &#39;success&#39;,<br>   errors: {},<br>  };<br> } catch (error) {<br>  if (error instanceof AuthError) {<br>   switch (error.type) {<br>    case &#39;CredentialsSignin&#39;:<br>     return {<br>      message: &#39;credentials error&#39;,<br>      errors: {<br>       ...defaultValues,<br>       credentials: &#39;incorrect email or password&#39;,<br>      },<br>     };<br>    default:<br>     return {<br>      message: &#39;unknown error&#39;,<br>      errors: {<br>       ...defaultValues,<br>       unknown: &#39;unknown error&#39;,<br>      },<br>     };<br>   }<br>  }<br>  throw error;<br> }<br>}<br><br>export async function logout() {<br> await signOut();<br>}</pre><p>Now, we need to create the middleware.ts file inside our src folder. This file will run before any renderization of our components, that’s why this approach is preferrable instead of checking the authentication using the layout.tsx files.</p><pre>import NextAuth from &#39;next-auth&#39;;<br>import { authConfig } from &#39;@/auth.config&#39;;<br>import { DEFAULT_REDIRECT, PUBLIC_ROUTES, ROOT } from &#39;@/lib/routes&#39;;<br><br>const { auth } = NextAuth(authConfig);<br><br>export default auth((req) =&gt; {<br> const { nextUrl } = req;<br><br> const isAuthenticated = !!req.auth;<br> const isPublicRoute = PUBLIC_ROUTES.includes(nextUrl.pathname);<br><br> if (isPublicRoute &amp;&amp; isAuthenticated)<br>  return Response.redirect(new URL(DEFAULT_REDIRECT, nextUrl));<br><br> if (!isAuthenticated &amp;&amp; !isPublicRoute)<br>  return Response.redirect(new URL(ROOT, nextUrl));<br>});<br><br>export const config = {<br> matcher: [&#39;/((?!api|_next/static|_next/image|favicon.ico).*)&#39;],<br>};</pre><p>Here, we are retrieving if the user is authenticated for every route in our application and verifying the current path. If the user has a current session and tried to go back to the login page, they will be redirected back to the /protected page. If the user tries to access any route that isn’t public without a session, they will be redirected to the login page. You can use any matcher suitable for your application.</p><p>Now, you have a complete authentication flow using middleware!</p><p><strong>2. Tests with Jest / Testing Library</strong></p><p>First, we need to install some dependencies</p><pre>pnpm i jest jest-environment-jsdom ts-jest @testing-library/jest-dom @testing-library/react @testing-library/user-event @types/jest@types/node</pre><p>Create the jest.config.ts and jest.setup.ts in the root of the application:</p><pre>jest.config.ts<br><br>import type { Config } from &#39;jest&#39;;<br>import nextJest from &#39;next/jest.js&#39;;<br><br>const createJestConfig = nextJest({<br> dir: &#39;./&#39;,<br>});<br><br>const config: Config = {<br> coverageProvider: &#39;v8&#39;,<br> preset: &#39;ts-jest&#39;,<br> testEnvironment: &#39;jest-environment-jsdom&#39;,<br> testMatch: [&#39;**/__tests__/**/*.test.ts?(x)&#39;],<br> setupFilesAfterEnv: [&#39;&lt;rootDir&gt;/jest.setup.ts&#39;],<br>};<br><br>export default createJestConfig(config);</pre><pre>jest.setup.ts<br><br>import &#39;@testing-library/jest-dom&#39;;<br><br>global.TextEncoder = require(&#39;util&#39;).TextEncoder;<br>global.TextDecoder = require(&#39;util&#39;).TextDecoder;</pre><p>Inside your tsconfig.json file, add this inside “compilerOptions”:</p><pre>  &quot;types&quot;: [&quot;@testing-library/jest-dom&quot;]</pre><p>Now, create a folder in the root of the application called “__tests__”, with another folder called “mocks”. Here, we are going to create 3 files to mock our NextAuth files.</p><pre>__tests__/mocks/auth.ts<br><br>const NAMock = {<br> auth: {<br>  session: {<br>   jwt: true,<br>  },<br>  jwt: {<br>   secret: process.env.AUTH_SECRET,<br>  },<br> },<br> signIn: jest.fn(),<br> signOut: jest.fn(),<br> handlers: {<br>  GET: jest.fn(),<br>  POST: jest.fn(),<br> },<br>};<br><br>export const {<br> auth,<br> signIn,<br> signOut,<br> handlers: { GET, POST },<br>} = NAMock;</pre><pre>__tests__/mocks/next-auth-providers-credentials.ts<br><br>const Credentials = jest.fn();<br><br>export default Credentials;</pre><pre>__tests__/mocks/next-auth.ts<br><br>export class AuthError extends Error {<br> type: string;<br> constructor(type: string) {<br>  super(type);<br>  this.type = type;<br> }<br>}<br><br>const NextAuth = () =&gt; ({<br> auth: jest.fn(),<br> signIn: jest.fn(),<br> signOut: jest.fn(),<br> handlers: {<br>  GET: jest.fn(),<br>  POST: jest.fn(),<br> },<br> AuthError: AuthError,<br>});<br><br>export default NextAuth;</pre><p>Inside the jest.config.ts files, add a moduleNameMapper for this mocked files. The file should be like this:</p><pre>jest.config.ts<br><br>import type { Config } from &#39;jest&#39;;<br>import nextJest from &#39;next/jest.js&#39;;<br><br>const createJestConfig = nextJest({<br> dir: &#39;./&#39;,<br>});<br><br>const config: Config = {<br> coverageProvider: &#39;v8&#39;,<br> preset: &#39;ts-jest&#39;,<br> testEnvironment: &#39;jest-environment-jsdom&#39;,<br> testMatch: [&#39;**/__tests__/**/*.test.ts?(x)&#39;],<br> setupFilesAfterEnv: [&#39;&lt;rootDir&gt;/jest.setup.ts&#39;],<br> moduleNameMapper: {<br>  &#39;@/auth&#39;: &#39;&lt;rootDir&gt;/__tests__/mocks/auth.ts&#39;,<br>  &#39;next-auth/providers/credentials&#39;:<br>   &#39;&lt;rootDir&gt;/__tests__/mocks/next-auth-providers-credentials.ts&#39;,<br>  &#39;next-auth&#39;: &#39;&lt;rootDir&gt;/__tests__/mocks/next-auth.ts&#39;,<br> },<br>};<br><br>export default createJestConfig(config);</pre><p>Finally, we can create our test for the Root page! Create a folder inside src called “__tests__” with a root.test.tsx file.</p><pre>src/__tests__/root.test.tsx<br><br>import { fireEvent, render, screen } from &#39;@testing-library/react&#39;;<br><br>import Root from &#39;@/app/page&#39;;<br>import { login } from &#39;@/lib/actions&#39;;<br>import { loginSchema } from &#39;@/types/schema&#39;;<br><br>let formState: {};<br>const formData = new FormData();<br><br>formData.append(&#39;email&#39;, &#39;test@gmail.com&#39;);<br>formData.append(&#39;password&#39;, &#39;test1234&#39;);<br><br>const renderComponent = () =&gt; {<br> return render(&lt;Root /&gt;);<br>};<br><br>jest.mock(&#39;react-dom&#39;, () =&gt; ({<br> ...jest.requireActual(&#39;react-dom&#39;),<br> useFormState: (mockLoginAction: any, state: any) =&gt; {<br>  formState = state;<br>  return [<br>   formState,<br>   (formData: FormData) =&gt; {<br>    mockLoginAction(formData).then((newState: any) =&gt; {<br>     formState = newState;<br>    });<br>   },<br>  ];<br> },<br>}));<br><br>jest.mock(&#39;../lib/actions&#39;, () =&gt; ({<br> ...jest.requireActual(&#39;../lib/actions&#39;),<br> login: jest.fn((formData: FormData) =&gt; {<br>  const email = formData.get(&#39;email&#39;);<br>  const password = formData.get(&#39;password&#39;);<br><br>  const validatedFields = loginSchema.safeParse({<br>   email: email,<br>   password: password,<br>  });<br><br>  if (!validatedFields.success) {<br>   return Promise.resolve({<br>    message: &#39;validation error&#39;,<br>    errors: validatedFields.error.flatten().fieldErrors,<br>   });<br>  }<br><br>  return Promise.resolve({<br>   message: &#39;success&#39;,<br>   errors: {},<br>  });<br> }),<br>}));<br><br>describe(&#39;Root&#39;, () =&gt; {<br> it(&#39;should render root page&#39;, () =&gt; {<br>  renderComponent();<br> });<br><br> it(&#39;should grab the form components&#39;, () =&gt; {<br>  renderComponent();<br><br>  const emailInput = screen.getByPlaceholderText(&#39;email&#39;);<br>  const passwordInput = screen.getByPlaceholderText(&#39;password&#39;);<br>  const button = screen.getByRole(&#39;button&#39;);<br><br>  expect(emailInput).toBeInTheDocument();<br>  expect(passwordInput).toBeInTheDocument();<br>  expect(button).toBeInTheDocument();<br> });<br><br> it(&#39;should call login action on form submit&#39;, async () =&gt; {<br>  renderComponent();<br><br>  const emailInput = screen.getByPlaceholderText(&#39;email&#39;);<br>  const passwordInput = screen.getByPlaceholderText(&#39;password&#39;);<br>  const button = screen.getByRole(&#39;button&#39;);<br><br>  fireEvent.input(emailInput, {<br>   target: { value: &#39;test@gmail.com&#39; },<br>  });<br>  expect(emailInput).toHaveValue(&#39;test@gmail.com&#39;);<br><br>  fireEvent.click(button);<br>  expect(login).not.toHaveBeenCalled();<br><br>  fireEvent.input(passwordInput, { target: { value: &#39;test1234&#39; } });<br>  expect(passwordInput).toHaveValue(&#39;test1234&#39;);<br><br>  fireEvent.click(button);<br><br>  expect(login).toHaveBeenCalled();<br> });<br>});</pre><p>Here, we have a complete test for our Root page, with the mocks for the login server action and useFormState hook. Run ‘pnpm run jest’, and watch all the tests pass:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*j4x-rm7U2fvbBn_ZMgN-mw.png" /></figure><p>In this article, you learned how to implement authentication with NextAuth v5, and also how to test your application with correct mocks. If this content helped you in any way, consider giving a star to the GitHub repository (<a href="https://github.com/renanleonel/next-auth-v5-middleware">https://github.com/renanleonel/next-auth-v5-middleware</a>). Thank you for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ca3e64bfb7d5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Customize SVGs using Next.js and Tailwind CSS]]></title>
            <link>https://medium.com/@renanleonel/how-to-customize-svgs-using-next-js-and-tailwind-css-d429b0143fa2?source=rss-76d2ceb73f6c------2</link>
            <guid isPermaLink="false">https://medium.com/p/d429b0143fa2</guid>
            <category><![CDATA[svg]]></category>
            <category><![CDATA[tailwind-css]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[Renan Leonel]]></dc:creator>
            <pubDate>Wed, 18 Oct 2023 21:43:10 GMT</pubDate>
            <atom:updated>2023-10-18T21:43:31.153Z</atom:updated>
            <content:encoded><![CDATA[<p>This article aims to demonstrate how to customize SVG images using Next.js and Tailwind, without the need for external configurations or the use of auxiliary libraries like svgr/webpack.</p><p>For this tutorial, we’re using the following image: <a href="https://www.flaticon.com/free-icon-font/checkbox_3917076?related_id=3917076">https://www.flaticon.com/free-icon-font/checkbox_3917076?related_id=3917076</a></p><pre>&lt;svg xmlns=&quot;http://www.w3.org/2000/svg&quot; xmlns:xlink=&quot;http://www.w3.org/1999/xlink&quot; version=&quot;1.1&quot; id=&quot;Capa_1&quot; x=&quot;0px&quot; y=&quot;0px&quot; viewBox=&quot;0 0 512 512&quot; style=&quot;enable-background:new 0 0 512 512;&quot; xml:space=&quot;preserve&quot; width=&quot;512&quot; height=&quot;512&quot;&gt;<br>  &lt;g&gt;<br>    &lt;path d=&quot;M405.333,0H106.667C47.786,0.071,0.071,47.786,0,106.667v298.667C0.071,464.214,47.786,511.93,106.667,512h298.667   C464.214,511.93,511.93,464.214,512,405.333V106.667C511.93,47.786,464.214,0.071,405.333,0z M426.667,172.352L229.248,369.771   c-16.659,16.666-43.674,16.671-60.34,0.012c-0.004-0.004-0.008-0.008-0.012-0.012l-83.563-83.541   c-8.348-8.348-8.348-21.882,0-30.229s21.882-8.348,30.229,0l83.541,83.541l197.44-197.419c8.348-8.318,21.858-8.294,30.176,0.053   C435.038,150.524,435.014,164.034,426.667,172.352z&quot; /&gt;<br>  &lt;/g&gt;<br>&lt;/svg&gt;</pre><p>The default behavior of Next.js with the `&lt;Image&gt;` tag does not allow changing the `fill` property of the SVG. This becomes an issue when we need to change the color of an SVG image during mouse hover, for example, using Tailwind CSS classes like `fill-white` or `bg-white`. This approach doesn’t work because we’re not directly changing the `fill` property of the `&lt;svg&gt;`, and as of the writing of this article `(Next 13.5.4)`, the `&lt;Image/&gt;` tag doesn’t support changes to the fill of SVGs.</p><pre>import Image from &#39;next/image&#39;;<br><br>import checkbox from &#39;../../public/icons/checkbox.svg&#39;;<br><br>const Home = () =&gt; {<br>  return (<br>    &lt;main className=&#39;h-screen bg-zinc-800 flex items-center justify-center&#39;&gt;<br>      &lt;Image<br>        src={checkbox}<br>        alt=&#39;checkbox&#39;<br>        className=&#39;w-20 h-20 fill-white&#39;<br>      /&gt;<br>    &lt;/main&gt;<br>  );<br>}<br><br>export default Home;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1WHvWMgEy4MonL4-Pgdv4w.png" /></figure><p>To solve this issue, we need to create a component for the SVG, removing style properties from the SVG tag, such as `width`, `height`, and primarily `fill`. These properties will be passed to the SVG through the `className` property of the component. Here’s how to do it:</p><pre>import { twMerge } from &#39;tailwind-merge&#39;;<br><br>interface CheckboxProps {<br>  className?: string;<br>}<br><br>const Checkbox = ({ className }: CheckboxProps) =&gt; {<br>  return (<br>    &lt;svg<br>      xmlns=&#39;http://www.w3.org/2000/svg&#39;<br>      version=&#39;1.1&#39;<br>      id=&#39;Capa_1&#39;<br>      x=&#39;0px&#39;<br>      y=&#39;0px&#39;<br>      viewBox=&#39;0 0 512 512&#39;<br>      width=&#39;512&#39;<br>      height=&#39;512&#39;<br>      className={twMerge(&#39;w-20 h-20&#39;, className)}<br>    &gt;<br>      &lt;g&gt;<br>        &lt;path d=&#39;M405.333,0H106.667C47.786,0.071,0.071,47.786,0,106.667v298.667C0.071,464.214,47.786,511.93,106.667,512h298.667   C464.214,511.93,511.93,464.214,512,405.333V106.667C511.93,47.786,464.214,0.071,405.333,0z M426.667,172.352L229.248,369.771   c-16.659,16.666-43.674,16.671-60.34,0.012c-0.004-0.004-0.008-0.008-0.012-0.012l-83.563-83.541   c-8.348-8.348-8.348-21.882,0-30.229s21.882-8.348,30.229,0l83.541,83.541l197.44-197.419c8.348-8.318,21.858-8.294,30.176,0.053   C435.038,150.524,435.014,164.034,426.667,172.352z&#39; /&gt;<br>      &lt;/g&gt;<br>    &lt;/svg&gt;<br>  );<br>};<br><br>export default Checkbox;</pre><p>Finally, our `page.tsx` file will look like this:</p><pre>import Image from &#39;next/image&#39;;<br>import Checkbox from &#39;@/components/svg/Checkbox&#39;;<br>import checkbox from &#39;../../public/icons/checkbox.svg&#39;;<br><br>const Home = () =&gt; {<br>  return (<br>    &lt;main className=&#39;h-screen bg-zinc-800 flex items-center justify-center gap-6&#39;&gt;<br>      &lt;Image<br>        src={checkbox}<br>        alt=&#39;checkbox&#39;<br>        className=&#39;w-20 h-20 fill-white&#39;<br>      /&gt;<br>      &lt;Checkbox className=&#39;fill-white hover:fill-red-600&#39; /&gt;<br>    &lt;/main&gt;<br>  );<br>};<br><br>export default Home;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KWlsle3tjmVV3jaBiMwHPg.png" /></figure><p>Now, we can customize our SVG according to external application states and user actions, such as hover. It’s a simple solution, but not very intuitive, as Next.js’ `&lt;Image/&gt;` tag doesn’t handle this kind of scenario effectively.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d429b0143fa2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Como realizar o deploy de uma aplicação Next.js com Next Auth na Heroku]]></title>
            <link>https://medium.com/@renanleonel/como-realizar-o-deploy-de-uma-aplica%C3%A7%C3%A3o-next-js-com-next-auth-na-heroku-c20214339005?source=rss-76d2ceb73f6c------2</link>
            <guid isPermaLink="false">https://medium.com/p/c20214339005</guid>
            <category><![CDATA[nextauth]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[heroku]]></category>
            <dc:creator><![CDATA[Renan Leonel]]></dc:creator>
            <pubDate>Sun, 01 Oct 2023 16:51:45 GMT</pubDate>
            <atom:updated>2023-10-01T16:51:45.750Z</atom:updated>
            <content:encoded><![CDATA[<p>Este é um breve tutorial de como realizar o deploy no serviço cloud Heroku de uma aplicação Next.js utilizando Next Auth como método de autenticação de usuários. A versão do Next.js utilizada é a versão 13.5.1, versão mais recente até a data de publicação do artigo .</p><h3>1) Primeiros passos</h3><p>Primeiramente, devemos ter um projeto Next.js publicado no Github, assim como uma conta na Heroku. Ao entrar na sua conta, você irá se deparar com a opção de criar um novo aplicativo:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2tDl_MDHTBsg7RbpAmRHAw.png" /></figure><p>Insira o nome do seu projeto e a região em que seu aplicativo será hospedado. No meu caso optei por hospedar nos Estados Unidos, mas selecione a opção que melhor se encaixa nos seus requisitos.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/653/1*N6PTEm8dqtNa4JnJLuS34Q.png" /></figure><h3>2) Conectando com o Github</h3><p>Após isso, devemos conectar a conta do Github em que o projeto se encontra.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/565/1*k44FFLeNKcUvigQjPpmFpg.png" /></figure><p>Após conectar com o Github, selecione o repositório que deseja fazer o deploy e selecione o botão Connect. Nesta parte também é possível habilitar o deploy automático toda vez que houver alterações na branch principal (main).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ijUFa2BUW83IvZ5pdqgQUw.png" /><figcaption>Deploys automáticos habilitados a partir da branch main</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*dSMr3o4jvfQoDH9QaJ-3vQ.png" /></figure><h3>3) Definir Variáveis de Ambiente</h3><p>Agora, vamos para a parte mais importante deste tutorial, a definição das variáveis de ambiente. Vá nas configurações do projeto:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*x2voPON1qzh3GJvEO3Tnng.png" /></figure><p>Na seção “Config Vars”, pressione o botão “Reveal Config Vars”.</p><p>No projeto Next.js, estou usando como exemplo as variáveis de ambiente do Next Auth da seguinte forma:</p><pre>NEXTAUTH_URL=http://localhost:3000<br>NEXTAUTH_SECRET=123</pre><p>Adicione as variáveis de ambiente na Heroku da seguinte forma:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/815/1*BdDCPE-N8vZly2Rd875FKw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/817/1*RLXqSlJ2jNeC98QiFXENcA.png" /></figure><p>A variável de ambiente NEXTAUTH_URL apontando para o localhost será apenas provisória enquanto não realizamos o primeiro deploy. Após o deploy, será necessário alterar o valor para o link gerado pela Heroku.</p><p>Em seguida, salve as variáveis de ambiente e realize seu primeiro deploy manual:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/989/1*fgTvKuULeAelyTJSmdkj_g.png" /></figure><p>Este processo pode demorar um pouco, então aguarde o deploy ser realizado. Ao finalizar, clique no botão “View” para ser redirecionado para a URL do seu projeto. Parabéns, você realizou seu primeiro deploy de um projeto Next.js na Heroku! Porém, para que a autenticação funcione corretamente, devemos alterar o valor da variável de ambiente que apontava para o localhost, apontando-a agora para a sua URL da Heroku.</p><h3>4) Atualizar a Variável de Ambiente para a URL da Heroku</h3><p>Copie a URL do seu projeto, vá para “Settings”, na seção “Config Vars” pressione o botão “Reveal Config Vars”. Altere a variável NEXTAUTH_URL com a URL do seu projeto Heroku. Por fim, realize outro deploy manual, e seu projeto deve funcionar corretamente.</p><h3>Considerações Finais</h3><p>Parabéns, você realizou seu deploy com Next Auth! Caso tenha habilitado os deploys automáticos, qualquer alteração na branch main do seu projeto realizará o deploy automático para produção, portanto tenha cuidado! Caso esteja utilizando outros serviços e/ou bibliotecas que necessitem de variáveis de ambiente, não se esqueça de adicioná-las no projeto na Heroku, caso contrário as integrações podem não funcionar como esperado.</p><p>Obrigado por ler até aqui!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c20214339005" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>