In this episode, we're diving into the differences between x-show
and x-if
in Alpine.js (these are two ways to conditionally show and hide content). You might have noticed we've been using x-show
a lot in this course, but there's also x-if
, and while they seem pretty similar, there are some key differences worth understanding.
First, we revisit the basics of x-show
with a simple example—a button that toggles the visibility of a message. After refreshing our memory, we copy this component and rewrite it to use x-if
, showing how the setup is a little different (especially needing a <template>
tag), but the visible result looks just the same.
But here's where things get interesting: we explore why you'd ever want to choose x-if
over x-show
. It all comes down to performance and when the code "inside" your condition gets run. With x-show
, your content is always rendered in the DOM (it's just hidden or shown), so if you have a costly calculation, it will run every time, even when hidden. With x-if
, the content (and its calculations) don't even exist until the condition is true—nothing is run until you need it.
To make this concrete, we walk through an example of rendering a user list sorted by points. By moving the expensive sorting calculation inside an x-if
, it's only triggered when the list is shown, not before. We use some simple console logs and switching between getter and method functions to really highlight this difference.
In short: use x-if
when you have something inside your markup that you don't even want to run until it's needed (like expensive calculations or API calls). Use x-show
for simple cases where you just want to show/hide things that are already lightweight and don't have costly side effects.
By the end of this episode, you'll know exactly when to reach for x-if
and when x-show
is good enough!