Tag: frontend development

  • Vue 3 Reactivity: State, Derived Values and Effects Without Surprises

    Vue 3 Reactivity: State, Derived Values and Effects Without Surprises

    Vue's reactivity system connects state reads to the effects that depend on them. When reactive state changes, Vue can update the relevant component render and invalidate derived values. This removes a great deal of manual DOM synchronisation, but it does not remove the need to decide what the source of truth is, which values are derived and where side effects belong.

    In Vue 3, reactive objects use JavaScript Proxy, while refs use getter and setter access around .value. Dependency tracking happens at runtime as an effect reads reactive properties (Vue — Reactivity in Depth).

    Article map for Vue 3 Reactivity: State, Derived Values and Effects Without Surprises, covering Separate state, derived values and effects, Choose ref and reactive deliberately, Use watchers for effects, not duplicate d…
    Article map: Separate state, derived values and effects; Choose ref and reactive deliberately; Use watchers for effects, not duplicate derivation; Keep state close until it is genuinely shared.

    Separate state, derived values and effects

    A maintainable component usually contains three distinct ideas:

    • State: the smallest mutable source of truth, such as a search term or selected identifier.
    • Derived value: information calculated from state, such as a filtered list or total.
    • Effect: work outside pure derivation, such as a network request, persistence, analytics or focus management.

    Use ref() or reactive() for state, computed() for a derived value and watch() or watchEffect() for a side effect. If the same value can be calculated, storing a second mutable copy creates synchronisation bugs.

    <script setup>
    import { computed, ref, watch } from 'vue';
    
    const query = ref('');
    const records = ref([]);
    
    const visibleRecords = computed(() => {
      const needle = query.value.trim().toLowerCase();
      return needle
        ? records.value.filter((record) => record.name.toLowerCase().includes(needle))
        : records.value;
    });
    
    watch(query, (value) => {
      // Example side effect: update a URL or schedule a request.
      // Keep cancellation and error handling explicit in production code.
      console.debug('Query changed', value);
    });
    </script>

    computed() caches its result based on reactive dependencies and should remain free of side effects. A computed getter that writes state, starts a request or changes the DOM is difficult to reason about and may run at unexpected times.

    Choose ref and reactive deliberately

    ref() can hold primitives or objects and exposes the value as .value in JavaScript. Templates generally unwrap top-level refs. It is often a simple default because the container can be replaced without losing the reactive connection.

    reactive() returns a proxy for an object. It is convenient for related fields, but the proxy identity differs from the original object, and replacing the whole variable with another raw object disconnects code that still references the previous proxy.

    A common pitfall is destructuring a primitive property from a reactive object:

    const state = reactive({ count: 0 });
    const { count } = state;
    
    state.count += 1;
    console.log(count); // The local binding is not reactive.

    Use toRef() or toRefs() when a property must remain linked through destructuring, or keep property access on the reactive object. Vue's documentation explains that destructured local bindings no longer trigger the source proxy's get/set traps (Vue — Reactivity in Depth).

    Do not mix raw and proxied versions as map keys or identity tokens without understanding the consequences. Use stable business identifiers for records rather than object identity when possible.

    Use watchers for effects, not duplicate derivation

    watch(source, callback) tracks an explicit source and gives access to current and previous values. watchEffect(callback) runs immediately and discovers dependencies while its synchronous body executes. An async watchEffect only tracks dependencies accessed before the first await, so explicit sources can be clearer for requests.

    Watchers are appropriate for:

    • fetching when an identifier changes;
    • synchronising selected state to the URL;
    • integrating with a non-Vue library;
    • persisting a bounded preference; and
    • triggering an accessible notification or focus change after a state transition.

    They are usually not needed to calculate display values. Use a computed property for that.

    Network effects need cancellation so a slow response for an old query does not overwrite a newer result. Vue watcher cleanup can abort stale work:

    watch(selectedId, async (id, _previous, onCleanup) => {
      if (!id) return;
    
      const controller = new AbortController();
      onCleanup(() => controller.abort());
    
      const response = await fetch(`/api/records/${encodeURIComponent(id)}`, {
        signal: controller.signal,
      });
    
      if (!response.ok) throw new Error(`Request failed: ${response.status}`);
      record.value = await response.json();
    });

    Production code should also expose loading, empty, failure and retry states and distinguish an intentional abort from a user-visible error.

    Decision path for Vue 3 Reactivity: State, Derived Values and Effects Without Surprises, covering Use watchers for effects, not duplicate derivation, Keep state close until it is genuinely shared, Avoid cross-request st…
    Decision path: Use watchers for effects, not duplicate derivation; Keep state close until it is genuinely shared; Avoid cross-request state leakage in SSR; Optimise only after profiling updates.

    Keep state close until it is genuinely shared

    Local component state is easiest to own and dispose. Lift state to a common parent or use a composable when several components share one workflow. Avoid a global store for every field; global state increases lifetime and coupling.

    For a larger application, Pinia is the Vue team's recommended state-management library. It adds conventions, development tooling, hot module replacement and server-side rendering support (Vue — State Management). Put business actions with meaningful names in the store rather than allowing arbitrary mutation from every component.

    State that comes from a server is not automatically client-owned truth. Define refresh, invalidation, optimistic update and conflict behaviour. Do not persist access tokens or sensitive records to browser storage merely because a store plugin makes persistence convenient.

    Avoid cross-request state leakage in SSR

    In a purely client-rendered application, a module-level singleton is new for each page load. In server-side rendering, application modules can be reused across requests. If user-specific state lives in one shared singleton, one request can leak into another.

    Vue recommends creating a new application and store instance for each SSR request and providing it to that request's component tree (Vue — Server-Side Rendering). Hydration also requires the server and client to begin with compatible state and markup.

    Serialised initial state is untrusted input when it reaches the browser. Encode it safely and avoid placing secrets in HTML.

    Optimise only after profiling updates

    Vue is efficient for ordinary interfaces. If updates are slow, first inspect Vue DevTools and browser performance traces to identify which components and data structures are involved.

    Useful patterns include:

    • keep props stable so unrelated children do not update;
    • give list items stable keys based on identity;
    • virtualise lists with thousands of visible candidates;
    • avoid rendering data the user cannot see;
    • split large asynchronous components where it improves initial delivery;
    • use shallowRef() or shallowReactive() for very large, deeply nested immutable structures; and
    • replace a shallow root value rather than mutating nested fields.

    Vue's performance guide notes that deep reactivity overhead becomes relevant for large structures with very many property accesses; shallow APIs trade convenient nested mutation for root-level replacement (Vue — Performance). Do not reach for them before measurements show a problem.

    Also consider page-load architecture. Vue advises against shipping a pure client-side SPA for content-sensitive marketing pages when server-rendered or static HTML can show useful content sooner. A project can use different rendering strategies for different routes.

    Control and evidence map for Vue 3 Reactivity: State, Derived Values and Effects Without Surprises, covering Avoid cross-request state leakage in SSR, Optimise only after profiling updates, Test behaviour through the us…
    Control and evidence map: Avoid cross-request state leakage in SSR; Optimise only after profiling updates; Test behaviour through the user's interface; General-information disclaimer.

    Test behaviour through the user's interface

    Test composables and deterministic business functions in isolation, then test components through roles, labels and visible outcomes. Include loading, error, empty and stale-response cases. Browser tests should cover a focused set of complete journeys and verify keyboard and focus behaviour.

    Do not assert private ref names or exact component trees unless they are genuinely part of a supported contract. A refactor should not destroy the suite if the user-visible behaviour remains correct.

    For help designing or reviewing a Vue interface and its API integration, see Ozlin Info's web development services or contact Ozlin Info.

    Related reading: Testing web applications: a risk-based strategy that scales.


    General-information disclaimer

    This article provides general technical information only. Patterns must be validated against the actual Vue version, rendering architecture, data sensitivity and application requirements.

    AI-assistance disclosure

    AI tools assisted with source discovery, outlining and copyediting. A human reviewer must run and verify all code examples, framework statements, service claims and the publication decision before release. No maintainability or performance outcome is guaranteed.

    Practical checklist for Vue 3 Reactivity: State, Derived Values and Effects Without Surprises, covering Test behaviour through the user's interface, General-information disclaimer, AI-assistance disclosure and related r…
    Practical checklist: Test behaviour through the user's interface; General-information disclaimer; AI-assistance disclosure; Primary sources checked.

    Primary sources checked

    Source access date: 29 August 2026.

  • CSS Grid for Responsive Layouts: Structure Without Source-Order Tricks

    CSS Grid for Responsive Layouts: Structure Without Source-Order Tricks

    CSS Grid is a two-dimensional layout system for rows and columns. It is well suited to page regions, card collections, dashboards and components where alignment in both axes matters. The difficult part is not learning display: grid; it is choosing track rules that respond to content without hiding overflow, reordering meaning or creating brittle breakpoints.

    Start with semantic HTML in the order people should read and operate it. Use Grid to present that structure, not to repair a confusing document tree.

    Article map for CSS Grid for Responsive Layouts: Structure Without Source-Order Tricks, covering Think in tracks, not device categories, Understand the automatic minimum, Use named regions for page-level clarity and rel…
    Article map: Think in tracks, not device categories; Understand the automatic minimum; Use named regions for page-level clarity; Let auto-placement handle repeated content.

    Think in tracks, not device categories

    A grid container defines columns and rows. Items occupy grid cells and may span more than one track. Flexible fr units divide remaining space, while intrinsic keywords and minmax() let content influence track sizing.

    For a card collection that should use as many sensible columns as fit:

    .card-grid {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(min(100%, 18rem), 1fr));
      gap: clamp(1rem, 2vw, 1.75rem);
    }

    auto-fit creates repeated tracks and collapses empty ones. minmax() sets a lower and upper sizing rule, while min(100%, 18rem) prevents the minimum from forcing horizontal overflow in a container narrower than 18rem. The W3C Grid specification defines auto-fit, auto-fill, intrinsic track sizes and flexible lengths in the track sizing model (W3C — CSS Grid Layout Module Level 2).

    This content-led rule often removes several viewport breakpoints. It does not remove the need to test long words, translated text, zoom, narrow containers and unusually large content.

    Understand the automatic minimum

    A 1fr track is not always equivalent to minmax(0, 1fr). Grid items can contribute an automatic minimum based on their content, so a long unbreakable string or wide child can force overflow.

    For application layouts where a flexible track must be allowed to shrink, use:

    .app-shell {
      display: grid;
      grid-template-columns: minmax(0, 1fr) minmax(16rem, 24rem);
    }
    
    .app-shell > * {
      min-width: 0;
    }

    Do not apply overflow: hidden everywhere to disguise the symptom. That can clip focus indicators, menus and content. Fix the sizing constraint and define wrapping or scrolling for the component that genuinely needs it.

    Use named regions for page-level clarity

    Named grid areas can make a stable page composition easy to read:

    .page {
      display: grid;
      grid-template-areas:
        "header header"
        "main   aside"
        "footer footer";
      grid-template-columns: minmax(0, 1fr) minmax(16rem, 22rem);
      gap: 1.5rem;
    }
    
    .site-header { grid-area: header; }
    .main-content { grid-area: main; }
    .sidebar { grid-area: aside; }
    .site-footer { grid-area: footer; }
    
    @media (max-width: 48rem) {
      .page {
        grid-template-areas:
          "header"
          "main"
          "aside"
          "footer";
        grid-template-columns: minmax(0, 1fr);
      }
    }

    The breakpoint belongs to this layout's content, not a device brand. Test it at zoom and with the sidebar's longest realistic content.

    Grid areas can visually rearrange content, but CSS does not generally change the DOM reading or keyboard focus order. A visual sidebar that appears before the main content while remaining later in the DOM can confuse people who navigate sequentially. Keep the source order meaningful at every layout and avoid the order property or explicit placements that create a mismatch.

    Let auto-placement handle repeated content

    For a homogeneous list of cards, allow normal auto-placement rather than assigning coordinates to every item. The default row-flow follows source order. grid-auto-flow: dense can backfill visual gaps, but it may display a later item before an earlier one. That is risky when sequence matters, including articles, products, form steps and keyboard-focusable cards.

    Use dense packing only when every item is truly independent and verify reading, focus and visual order.

    If one featured item spans tracks, apply an explicit class based on content meaning, not an :nth-child() rule that changes unpredictably when editors add items.

    Decision path for CSS Grid for Responsive Layouts: Structure Without Source-Order Tricks, covering Use named regions for page-level clarity, Let auto-placement handle repeated content, Align nested components with subgr…
    Decision path: Use named regions for page-level clarity; Let auto-placement handle repeated content; Align nested components with subgrid; Use container queries for component context.

    Align nested components with subgrid

    Without subgrid, each card calculates its own internal rows. Headings of different length can move summaries and actions out of alignment. A nested grid using subgrid can inherit the parent track definition:

    .pricing-grid {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(min(100%, 17rem), 1fr));
      gap: 1rem;
    }
    
    .pricing-card {
      display: grid;
      grid-template-rows: subgrid;
      grid-row: span 4;
    }

    Subgrid participates in the sizing of the parent tracks, which is useful for aligned headings, feature lists and calls to action. Check the browser baseline required by the project and provide a reasonable non-subgrid layout where older embedded browsers remain in scope.

    Use container queries for component context

    Viewport media queries answer how wide the browser is. A component may appear in a full page, sidebar or modal within the same viewport. Container queries can adapt it to the space its parent provides:

    .profile-module {
      container-type: inline-size;
    }
    
    @container (min-width: 36rem) {
      .profile-card {
        grid-template-columns: 8rem minmax(0, 1fr);
      }
    }

    Grid and container queries solve different problems: Grid distributes space; a container query switches rules based on an ancestor's size. Use the smallest number of state changes that the component actually needs.

    Choose Grid, Flexbox or normal flow by relationship

    Use normal block and inline flow for text and simple documents. Use Flexbox where one-dimensional distribution and alignment is primary, such as a toolbar or button group. Use Grid where rows and columns form a meaningful two-dimensional relationship.

    They work together. A page can use Grid for regions, Flexbox for navigation controls and normal flow inside an article. Avoid turning every wrapper into a layout context; each level adds constraints and debugging work.

    Keep spacing and sizing resilient

    Prefer gap for space between grid tracks rather than margins that components must know how to cancel. Use clamp() for bounded fluid values where continuous scaling makes sense. Combine relative units with readable maximum line lengths.

    Do not fix card heights to make a screenshot align. Fixed heights break with larger text, localisation and user styles. Use track alignment and let content determine height. If a section legitimately scrolls, give it a visible boundary, keyboard access and an accessible name where needed.

    Images should have intrinsic dimensions or an aspect ratio so the grid does not move after they load. Use object-fit only when cropping is acceptable and make sure important content is not lost at different aspect ratios.

    Control and evidence map for CSS Grid for Responsive Layouts: Structure Without Source-Order Tricks, covering Use container queries for component context, Choose Grid, Flexbox or normal flow by relationship, Keep spacin…
    Control and evidence map: Use container queries for component context; Choose Grid, Flexbox or normal flow by relationship; Keep spacing and sizing resilient; Test more than three viewport screenshots.

    Test more than three viewport screenshots

    A robust layout test includes:

    • narrow and wide containers, including component reuse;
    • 200% text enlargement and 400% browser zoom;
    • long headings, URLs and untranslated strings;
    • missing images, short content and very long content;
    • right-to-left direction where relevant;
    • keyboard focus indicators near clipped or overlapping regions;
    • browser minimums in the support policy; and
    • print or reduced-motion modes where the service needs them.

    Use browser development tools to inspect grid lines and track sizing, but verify through real content and assistive-technology tasks. A visually aligned grid is not automatically a usable information hierarchy.

    For help implementing a responsive design system or repairing a brittle layout, see Ozlin Info's web development services or contact Ozlin Info.

    Related reading: Web accessibility with WCAG 2.2: a practical delivery guide.


    General-information disclaimer

    This article provides general technical information only. CSS behaviour and support must be tested against the project's actual browsers, content, accessibility requirements and component contexts.

    AI-assistance disclosure

    AI tools assisted with source discovery, outlining and copyediting. A human reviewer must run every code example, test the target browser matrix and verify service claims and the publication decision before release. No cross-browser or accessibility outcome is guaranteed.

    Practical checklist for CSS Grid for Responsive Layouts: Structure Without Source-Order Tricks, covering Test more than three viewport screenshots, General-information disclaimer, AI-assistance disclosure and related re…
    Practical checklist: Test more than three viewport screenshots; General-information disclaimer; AI-assistance disclosure; Primary sources checked.

    Primary sources checked

    Source access date: 29 August 2026.