Syntax // Frontend_Patterns

A memory dump of JavaScript and JSX patterns I use instinctively. Useful for React, Astro, Next.js, or any modern frontend stack.

We all have those pieces of code we write instinctively, and those we have to Google every single time.

This is a collection of my “daily drivers” - snippets that make the codebase cleaner, safer, and easier to read. No complex libraries, just pure utility logic.

01. The “Curried” Event Handler

Passing parameters to event handlers often leads to messy inline arrow functions like onClick={(e) => handleClick(slug, e)}. There is a cleaner way using a technique called Currying.

// The Definition
// We create a function that returns another function
const handleDetailClick = (slug: string) => (e: React.MouseEvent<HTMLElement>) => {
    // 1. Meta key check (CMD/CTRL + Click opens in new tab)
    if (e.metaKey || e.ctrlKey) {
        return;
    }

    e.preventDefault();
    navigate(slug);
};

// The Usage (Clean & Readable)
// No need to manually pass the 'event' object
<button onClick={handleDetailClick('post-slug-01')}>
    Open Detail
</button>

02. Immutable Deletion

When working with React state, you should never mutate the array directly (e.g., splice). Instead, use .filter() to create a new array that contains everything except the item you want to remove.

// Remove 'targetValue' from the list
const newFilterList = filterReserveStockList.filter(
  (item) => item !== targetValue,
);

03. Short-Circuit Rendering

Stop using ternary operators returning null when you just want to render something conditionally. It adds unnecessary noise to the JSX.

// ❌ Old School (Noisy)
{
  !loading ? <>Loading...</> : null;
}

// ✅ Clean (Short-Circuit)
{
  !loading && <>Loading...</>;
}

Sometimes you need to check if an object contains a key that matches a specific pattern—either an exact match or a prefix.

const attributes = {
  color: "blue",
  size_xl: true,
  weight_kg: 20,
};

const name = "size";

// Returns TRUE because "size_xl" starts with "size"
const hasMatchingKey = Object.keys(attributes).some(
  (key) => key === name || key.startsWith(name),
);

Note: .some() is efficient because it stops iterating as soon as it finds the first match.

05. URL Safety

Never trust user input inside a URL string. Spaces, slashes, or special characters (&, ?) will break your routing parameters if not encoded.

const userInput = "DayZ & Coffee";

// ❌ Bad: Result is "/search?q=DayZ & Coffee" (Breaks query)
const badUrl = `/search?q=${userInput}`;

// ✅ Good: Result is "/search?q=DayZ%20%26%20Coffee"
const safeUrl = `/search?q=${encodeURIComponent(userInput)}`;

06. Dynamic Page Titles

In Single Page Applications (SPAs), we often forget to update the browser tab title when the user navigates. It’s a small detail that improves UX significantly.

// Ideally placed inside a useEffect hook
document.title = `${titleValue} | Arfour.xyz`;

07. The Sorting Protocol

Sorting logic can be confusing. Here is a breakdown using a fake inventory list.

The logic relies on returning 1, -1, or 0.

  • -1: Item A should come before Item B.
  • 1: Item A should come after Item B.
const inventory = [
  { name: "Zenith_Chip" },
  { name: "Alloy_Plate" },
  { name: "Cyberdeck_v1" },
  { name: "Blade_Runner" },
];

// 🔽 CASE A: Sort A -> Z (Ascending)
const sortedAsc = [...inventory].sort((a, b) => {
  // If A is "smaller" (comes first in alphabet), move it UP (-1)
  return a.name < b.name ? -1 : 1;
});
// Result: Alloy, Blade, Cyberdeck, Zenith

// 🔼 CASE B: Sort Z -> A (Descending)
const sortedDesc = [...inventory].sort((a, b) => {
  // If A is "smaller", move it DOWN (1)
  return a.name < b.name ? 1 : -1;
});
// Result: Zenith, Cyberdeck, Blade, Alloy

Pro Tip: For numbers, you can simply use subtraction: (a, b) => a - b (Ascending) or (b, a) => b - a (Descending).

08. Fragment Cleanup

Avoid “Div Soup” - wrapping everything in unnecessary <div> tags just to satisfy the JSX requirement of a single parent. Use Fragments to group elements without adding extra nodes to the DOM.

// ❌ Dirty: Adds an extra useless <div> to the DOM
const BadWrapper = () => (
  <div>
    <Header />
    <Content />
  </div>
);

// ✅ Clean: No extra nodes in DOM
const CleanWrapper = () => (
  <>
    <Header />
    <Content />
  </>
);
import { Fragment } from "react"; // Or 'preact', 'astro/jsx-runtime'

// 🚀 Advanced: Fragments inside .map() loops
{
  items.map((item) => (
    <Fragment key={item.id}>
      <dt>{item.term}</dt>
      <dd>{item.definition}</dd>
    </Fragment>
  ));
}

Important: The short syntax <> does not support keys. If you are mapping over an array and need to return multiple elements without a wrapper, you must import Fragment and use <Fragment key={id}>.

09. The Dictionary Lookup

Replace messy switch statements or endless if/else chains with a clean Object Lookup (Dictionary). It makes the logic declarative and much easier to extend later.

const status = "error";

// ❌ Old School: Verbose Switch
const getColorSwitch = (status) => {
  switch (status) {
    case "success":
      return "green";
    case "warning":
      return "orange";
    case "error":
      return "red";
    default:
      return "gray";
  }
};

// ✅ Clean: Object Lookup
const statusColors = {
  success: "green",
  warning: "orange",
  error: "red",
};

// One-line magic (with fallback)
const color = statusColors[status] || "gray";

Why: It transforms procedural logic (“if this then do that”) into configuration data (“key maps to value”).

10. Conditional Classes (The UI Switch)

Don’t clutter your DOM with unused event listeners or hover classes on active items. Use a template literal to switch the entire state.

<span
  className={`font-mono text-lg font-bold ${
    active
      ? "cursor-default text-white" // Active State
      : "cursor-pointer text-gray-400 transition-colors duration-300 hover:text-white" // Inactive (Hover) State
  } `}
>
  {title}
</span>

System :: Feedback loop

Did these snippets optimize your workflow? Initiate the ack_ sequence on the button below.

High signal strength ensures the compilation of Part II.

usr_ack:
<incoming_signal HTML // Forgotten_Tag_<wbr> previous_transmission> DayZ :: PBO_Error