JavaScript Closure Explained with a Real React Example (Movie Ticket Booking)
JavaScript Closures in React – Movie Ticket Booking (Silver & Gold)
In this blog, we will understand JavaScript closures using
very small code snippets, and then connect it to a real
React movie ticket booking screen with Silver & Gold seats.
We’ll also use the useState lazy initializer pattern.
🎥 Watch the Video Explanation
I have a full video on my YouTube channel where I explain this same concept with live coding. You can watch it here:
You can also visit my channel: @CodeWithSanyogita
1. Start with a Tiny Closure
First, forget React. Let’s build the smallest closure example.
// Step 1: Outer function
function createCounter() {
let count = 0; // local variable
// Step 2: Return inner function
return function () {
count = count + 1;
return count;
};
}
// Step 3: Use it
const counter = createCounter();
console.log(counter()); // 1
console.log(counter()); // 2
console.log(counter()); // 3
Why is this a closure?
countis insidecreateCounter.- We return an inner function that uses
count. - Even after
createCounter()finished, the inner function still remembers the last value ofcount.
A closure is a function that remembers variables from the place where it was created.
2. Add a Label: Silver & Gold Style
Now let’s add a label. This will help us later for Silver and Gold tickets.
function createLabeledCounter(label) {
let count = 0;
return function () {
count = count + 1;
console.log(label, "count is", count);
return count;
};
}
const silverCounter = createLabeledCounter("SILVER");
const goldCounter = createLabeledCounter("GOLD");
silverCounter(); // "SILVER count is 1"
silverCounter(); // "SILVER count is 2"
goldCounter(); // "GOLD count is 1"
Each counter:
- Has its own
countvariable. - Remembers that count through the inner function.
- Is a separate closure
👩💻 Written by Code With Sanyogita
Frontend Developer & content creator sharing beginner-friendly tutorials on React, JavaScript, and Web Development.
If this post helped you, consider subscribing on YouTube for more real-world coding examples 🚀
Comments
Post a Comment
Share your doubt or feedback below 👇