📖 Scenario: You are building a Next.js app that shows a list of blog posts fetched from an API. To improve performance, you want to cache the posts but also update the cache when new posts are added or existing posts change.
🎯 Goal: Build a Next.js component that fetches blog posts, caches them using useState, and implements a simple cache invalidation strategy to refresh the posts every 10 seconds.
📋 What You'll Learn
Create a state variable to hold the list of posts
Create a variable for the cache refresh interval (10 seconds)
Use useEffect to fetch posts and update the cache
Set up a timer to invalidate the cache and refetch posts every 10 seconds
💡 Why This Matters
🌍 Real World
Caching and cache invalidation are important for improving app performance and ensuring users see fresh data without unnecessary delays.
💼 Career
Understanding cache invalidation strategies is valuable for frontend developers working with data fetching in React and Next.js apps to build efficient and user-friendly interfaces.
Progress0 / 4 steps
1
Set up initial posts state
Create a state variable called posts using useState and initialize it as an empty array.
NextJS
Hint
Use const [posts, setPosts] = useState([]) inside the component.
2
Add cache refresh interval variable
Inside the BlogPosts component, create a constant called refreshInterval and set it to 10000 (milliseconds).
NextJS
Hint
Use const refreshInterval = 10000; inside the component.
3
Fetch posts and update cache
Use useEffect to fetch posts from 'https://jsonplaceholder.typicode.com/posts' and update the posts state using setPosts. Fetch the posts once when the component mounts.
NextJS
Hint
Inside useEffect, create an async function to fetch posts and call it immediately.
4
Add cache invalidation with interval
Extend the useEffect to set up an interval that refetches posts every refreshInterval milliseconds. Clear the interval when the component unmounts.
NextJS
Hint
Use setInterval inside useEffect to call fetchPosts repeatedly, and clear it on cleanup.
Practice
(1/5)
1. In Next.js, which method allows you to update static pages after a certain time interval to keep data fresh without rebuilding the entire site?
easy
A. getServerSideProps without caching
B. Manually clearing browser cache
C. Using client-side useEffect to fetch data
D. getStaticProps with revalidate
Solution
Step 1: Understand Next.js data fetching methods
getStaticProps generates static pages at build time, but with revalidate, it can update pages after a set interval.
Step 2: Compare with other methods
getServerSideProps fetches fresh data on every request but does not use caching or revalidation intervals.