🔥 (235) Hidden Component Pattern, UI states, and Dedupe fetches in Nuxt

​ ​

Read this on my blog

Hey all!

This week I've got a couple of articles for you, as well as some tips.

I'm just getting started on my next project for Mastering Nuxt. You'll find out more about that soon enough.

Enjoy the newsletter!

— Michael

Clean Components Toolkit

Are your Vue components getting messy and hard to maintain? Struggling with when to split components or how to organize your code?

The Clean Components Toolkit teaches you battle-tested patterns and principles to write cleaner, more maintainable Vue apps, including:

  • 3.5 + hours of focused video content plus comprehensive written materials
  • Step-by-step refactoring examples showing real-world applications
  • Interactive quizzes to reinforce your learning
  • 20 + practical tools and patterns for component organization
  • Lifetime access to updates and new content

You'll master:

  • Component splitting and combining — when (and when not) to break up components
  • State management across components — especially as complexity grows
  • Logic organization and reuse — using the three core component types
  • Seamless refactoring techniques — transform messy code into clean, maintainable components
"The Clean Components Toolkit's concise, to-the-point lessons made the learning process feel effortless and led to a deeper understanding of the subject matter." — Alex Rodriguez

Master Clean Components Now →

🔥 The Hidden Component Pattern

Looking at a component itself is the primary way that we can figure out when and how to refactor it. But we can also look at how the component is used for some clues.

Specifically, we're looking to see if there are subsets of this component where those features are only used together.

This suggests that there may be more than one component hidden inside of this one.

Let's say we have the following component:

<template>    <div v-if="conditional">      <!-- ... -->    </div>    <div v-else>      <!-- ... -->    </div>  </template>

Because the v-if is at the root, we know that it's not actually adding any value to this component.

Instead, we can simplify by splitting into one component for each branch of our conditional:

<template>    <ComponentWhereConditionalIsTrue />    <ComponentWhereConditionalIsFalse />  </template>

Now, we don't need to hard-code the conditional prop — we can just use the more descriptive and specific component.

For another example, if prop1 and prop2 are only ever used together, but never with prop3 and prop4, it could mean that the functionality relying on prop1 and prop2 should be separated from the rest of the component.

In this illustration, the usage of MyComponent always uses two distinct sets of props, prop1 and prop2, or prop3 and prop4:

<MyComponent prop-1="someValue" prop-2="anotherValue" />    <MyComponent prop-1="hello" prop-2="world" />    <MyComponent :prop-3="34" prop-4 />

In our theoretical refactoring, we would split the component to work like this:

<FirstComponent prop-1="someValue" prop-2="anotherValue" />    <FirstComponent prop-1="hello" prop-2="world" />    <SecondComponent :prop-3="34" prop-4 />

Here are the steps to do this refactoring:

  • Look for how the component is being used
  • Identify any subsets of behaviour — props, events, slots, etc. — that don't overlap
  • Simplify using other patterns until it's easy to understand
  • Refactor into separate components based on the subsets of behaviour

Learn more about this pattern in the Clean Components Toolkit.

🔥 UI states to get right

When building a UI, there are many different states that you need to consider:

  • Normal — Sometimes called the "happy path," this is when things are working as expected. For example, in an email client, you'd show some read emails, some unread emails, and maybe a few that are in the "spam" folder.
  • Loading — Your UI has to do something while getting the data, right? A couple tricks:
  • 1. Use a computed prop to combine multiple loading states — you don't want spinners all over the page. 1. Wait about 200ms before showing a spinner. If the data loads before that, it feels faster than if you quickly flash the loading spinner on and then off again.
  • Error — Things will go wrong, and you need to handle that gracefully. Effectively communicating problems to users to help them get unstuck is very tricky (don't make me guess the password requirements!). Hopefully, you have a good UX designer.
  • Empty — What happens when you have no emails to read, have completed all your tasks, or haven't uploaded any videos yet? A chart showing the "Last 30 Days" of data will probably look weird with no data.
  • Partial Data — Often similar to the empty state, but your big table with filtering and sorting also needs to work with only two rows of data. The list of emails shouldn't break with only one email in it.
  • Lots of data — Okay, now you have 1294 unread emails. Does your UI break? Maybe that infinite scrolling doesn't make as much sense as when there were only 42 emails.

🔥 Dedupe fetches in Nuxt

Since 3.9 we can control how Nuxt deduplicates fetches with the dedupe parameter:

useFetch('/api/menuItems', {    // Cancel the previous request and make a new request    dedupe: 'cancel'  });

The useFetch composable (and useAsyncData composable) will re-fetch data reactively as their parameters are updated. By default, they'll cancel the previous request and initiate a new one with the new parameters.

However, you can change this behaviour to instead defer to the existing request — while there is a pending request, no new requests will be made:

useFetch('/api/menuItems', {    // Keep the pending request and don't initiate a new one    dedupe: 'defer'  });

This gives us greater control over how our data is loaded and requests are made.

📜 3 Kinds of Props in Vue

One of Vue's core features is the use of props. Props are how we pass data around in Vue, from parent to child components.

But not all props are created equal.

There are three main kinds:

  • Template Props
  • Configuration Props
  • State Props (or Data Props).

Check it out here: 3 Kinds of Props in Vue

📜 Nuxt State Management: Pinia vs useState

In Nuxt we get a new useState composable.

But how does it compare to Pinia?

In this article for Vue Mastery, I discuss the main differences and when to use each.

Check it out here: Nuxt State Management: Pinia vs useState

💬 Less Documentation

"The best reaction to "this is confusing, where are the docs" is to rewrite the feature to make it less confusing, not write more docs." — Jeff Atwood

🧠 Spaced-repetition: Debug hydration errors in production Nuxt

The best way to commit something to long-term memory is to periodically review it, gradually increasing the time between reviews 👨‍🔬

Actually remembering these tips is much more useful than just a quick distraction, so here's a tip from a couple weeks ago to jog your memory.

Hydration errors are one of the trickiest parts about SSR — especially when they only happen in production.

Thankfully, Vue 3.4 lets us do this.

In Nuxt, all we need to do is update our config:

export default defineNuxtConfig({    debug: true,    // rest of your config...  })

If you aren't using Nuxt, you can enable this using the new compile-time flag: VUEPRODHYDRATIONMISMATCHDETAILS.

This is what Nuxt uses.

Enabling flags is different based on what build tool you're using, but if you're using Vite this is what it looks like in your vite.config.js file:

import { defineConfig } from 'vite'    export default defineConfig({    define: {      __VUE_PROD_HYDRATION_MISMATCH_DETAILS__: 'true'    }  })

Turning this on will increase your bundle size, but it's really useful for tracking down those pesky hydration errors.

🔗 Want more Vue and Nuxt links?

Michael Hoffman curates a fantastic weekly newsletter with the best Vue and Nuxt links.

Sign up for it here.

p.s. I also have a bunch of products/courses:

Unsubscribe

评论

此博客中的热门博文

丁薛祥在“77国集团和中国”气候变化领导人峰会上的致辞(全文)

The magic of scoped slots in Vue ✨ (3/4)