Use Local Storage in React using hooks by building a progress tracker like Next.js' course page

Last updated on June 22, 2022

If you want a more beginner level tutorial regarding Local Storage, check out my other tutorial where I use plain Javascript and HTML.

What we'll build in order to utilise Local Storage

Couple of days ago I found a great use case for Local Storage that is being used in production. The Next.js website has section dedicated for short courses with multiple articles, sub articles, quizzes. In addition, every time you view an article and answer a quiz, your score increases.

While you go through the course, the website state update which helps us to remember our progress through the course by visually indicating which articles we have already read.

They record this information via Local Storage! Here's the JSON that I got after I visited the Local Storage tab in the developer tools.

  • Each Object key represents the path
  • They track two states - visited and checked are similar to each other. When you first visit a path, it's going to become "visited" and if the path doesn't have any sub lessons, it will also become "checked"
  • I assume that the score is calculated via an internal data source which is not visible to the user.
javascript
1
{
2
"ready": true,
3
"basics/create-nextjs-app": { "visited": true, "checked": true },
4
"basics/create-nextjs-app/setup": { "visited": true, "checked": true },
5
"basics/create-nextjs-app/welcome-to-nextjs": {
6
"visited": true,
7
"checked": true
8
},
9
"basics/navigate-between-pages": { "visited": true }
10
}
11

Let's explore how we can replicate this functionality using React, Local Storage and Hooks. We will have a sidebar of lessons for our course and every time a user reads a lesson, we will record it in our local storage so we can show that they have read it.

Note: For simplicity reasons, we are going to omit the visited and checked states and use only visited instead.

Step 1: Set up the test data

Let's begin by setting up a basic data for our course which will include 3 lessons. Each object will have an id and a name which represents a lesson.

javascript
1
// data.js
2
3
const data = [
4
{
5
id: "first-lesson",
6
name: "First Lesson",
7
},
8
{
9
id: "second-lesson",
10
name: "Second Lesson",
11
},
12
{
13
id: "third-lesson",
14
name: "Third Lesson",
15
},
16
];
17
18
export default data;

In this tutorial, we are using Next.js and TailwindCSS

Step 2: Set up routes and Local Storage

Step 2.1: Create a Layout.js file and set up Local storage

This file will act as a wrapper for our course pages. It does several things:

  • Render the data into a clickable list on the sidebar
  • On page load, it will either retrieve the "progress" items from your local storage or create a fresh object so we can put data in
  • While we are rendering the lessons list, we will check if this lesson has been viewed. If so, we will indicate it via a Check icon
javascript
1
import data from "../data";
2
import { useState, useEffect } from "react";
3
import Check from "./Check";
4
5
const Layout = ({ children }) => {
6
const [progress, setProgress] = useState({});
7
8
useEffect(() => {
9
let progress = JSON.parse(localStorage.getItem("progress")) || {};
10
setProgress(progress);
11
}, []);
12
13
return (
14
<div className="my-20 max-w-5xl mx-auto px-8">
15
<h1 className="text-center font-bold text-3xl">Local storage in React</h1>
16
<div className="grid grid-cols-5 gap-8 mt-12">
17
<ul className="col-span-2 bg-blue-100 p-4 rounded-lg">
18
{data.map((lesson) => {
19
return (
20
<li key={lesson.id}>
21
<a
22
href={`/course/${lesson.id}/`}
23
className="hover:underline font-semibold flex w-full justify-between items-center gap-2 hover:text-gray-700"
24
>
25
<span>- {lesson.name}</span>
26
27
{progress.hasOwnProperty(lesson.id) &&
28
progress[lesson.id].visited ? (
29
<Check />
30
) : null}
31
</a>
32
</li>
33
);
34
})}
35
</ul>
36
<div className="col-span-3 border border-dashed border-gray-300 p-8 rounded-lg">
37
<div>
38
<h2 className="text-2xl font-bold mb-4">Content</h2>
39
<div>{children}</div>
40
</div>
41
</div>
42
</div>
43
</div>
44
);
45
};
46
47
export default Layout;

2.2 Create individual lesson pages

  • We use a useEffect hook to retrieve the progress item from the Local Storage and the associated lesson path as visited
  • We then save this route within our Local Storage
javascript
1
// pages/course/[id].js
2
3
import { useEffect } from "react";
4
import data from "../../data";
5
import Layout from "../../components/Layout";
6
7
const Lesson = ({ lesson }) => {
8
// When you visit a lesson, mark it as visited
9
useEffect(() => {
10
// either create a new item or initialize a new one if the user doesn't have it
11
let progress = JSON.parse(localStorage.getItem("progress")) || {};
12
13
progress[lesson.id] = { visited: true };
14
15
localStorage.setItem("progress", JSON.stringify(progress));
16
}, [lesson.id]);
17
18
return <Layout>{lesson.name}</Layout>;
19
};
20
21
export const getStaticProps = async ({ params }) => {
22
const lesson = data.find((item) => item.id === params.id);
23
return {
24
props: { lesson },
25
};
26
};
27
28
export const getStaticPaths = async () => {
29
return {
30
paths: data.map((item) => {
31
return { params: { id: item.id } };
32
}),
33
fallback: false,
34
};
35
};
36
37
export default Lesson;

And voilà - we have a fully functioning tracking for our course. If the user has viewed the lesson, we will showcase a check icon next to this lesson with in the sidebar.

Step 3. Use packages to make your life easier

In this tutorial, we set up the local storage logic by ourselves using the useState and useEffect hooks. Thankfully, the React community is awesome and they have some great packages which wraps all the functionality you need in useful custom hooks.

Here are some of my favourites:

Next steps

You now know how to use Local Storage in React. Are you interested in improving your knowledge further on? Grab the source code of this project from Github and complete the following tasks

  1. Ability to have sub lessons
  2. Assign score to each page and total it together when a user visits a specific page
  3. Create a quiz at the bottom of one of the lessons and record the data in local storage, so the user can see that they have answered it and how they have answered it

You are welcome to submit your own repo by leaving a comment below.

Invite us to your inbox.

Articles, guides and interviews about web development and career progression.

Max 1-2x times per month.