Skip to content
Tutorials Center
My learning

Topics

Lesson 107 of 132 ยท Projects

Project: Markdown Notes App

Build a Markdown notes app in React: write a tiny Markdown renderer without dangerouslySetInnerHTML, edit notes with a reducer, add search and pinning, and simulate saving to storage.

A notes app is the project where all the earlier lessons meet. It has a list and a detail view, a form-like editor, derived data (search results, sorting), and the question every real app faces: how do I keep the data after the page closes? It also has a fun technical core. To show formatted notes you need a Markdown renderer, and in this project you will write a small one yourself that produces React elements, with no HTML strings and therefore no cross-site scripting risk.

The plan has four stages. First you build and test the renderer on its own. Then you add the note list and the editor with a reducer. Then search and pinning, which are pure derived state. Finally you add persistence, simulated in memory because our sandbox has no localStorage, and with the exact code you would use in a real app shown in a read-only block. Relevant background lessons are JSX in depth (escaping and dangerouslySetInnerHTML), forms and inputs, reducers and choosing state structure.

Step 1: a Markdown renderer that returns elements

Most Markdown libraries convert text to an HTML string, and then you have to inject that string with dangerouslySetInnerHTML. If the conversion misses one case, an attacker's <script> or onerror= attribute runs in your page. We will go the other way: convert the text into a list of plain JavaScript objects (the blocks), then render those blocks as normal JSX. React escapes every string it renders, so user text can never become markup.

The renderer supports a deliberately small subset:

Syntax Result
# Title, ## Title, ### Title Headings level 1 to 3
- item or * item Bulleted list
> text Block quote
blank line Separates blocks
**bold**, *italic*, `code` Inline styles
[label](https://...) Link (only http, https or # targets)

Parsing happens in two layers. parseBlocks walks the text line by line and groups lines into blocks: a heading is a single line, consecutive list lines join one list, consecutive paragraph lines join one paragraph. renderInline then handles the inside of one block by splitting the string on a regular expression that captures the special pieces, so the split result alternates between plain text and styled pieces.

JavaScript
const INLINE = /(`[^`]+`|\*\*[^*]+\*\*|\*[^*]+\*|\[[^\]]+\]\([^)]+\))/g;
'a **b** c'.split(INLINE); // ['a ', '**b**', ' c']

The renderer is a pure function of its input: the same text always gives the same elements. Because of that, using the array index as a key is safe here; the blocks have no state and are never reordered independently (the rule from lists and keys is about identity, and identity does not matter for stateless output). The live editor below lets you type Markdown and see the result. The sample includes a <script> tag and a javascript: link to prove that both stay inert.

Stage 1: a Markdown renderer without HTML strings

The console shows the block types found in the sample (heading, paragraph, list, quote, paragraph). In the preview the <script> tag appears as literal text, and the javascript: link is not a link at all: isSafe accepted only http(s) and # targets. That check matters. Without it a note could contain [click me](javascript:...), which would run code when clicked.

A hand-written renderer is great for learning and for tiny subsets. For production Markdown (tables, nested lists, code fences, reference links) use a maintained library that returns React elements, and keep the habit of never inserting HTML strings you did not sanitize (JSX in depth).

Step 2: notes, selection and the editor

Now the application. Decide the state first:

JavaScript
{
  nextId: 3,
  notes: [{ id: 1, title: 'Weekend plan', body: '...', pinned: false, updated: 1 }],
  clock: 2,
}

Each note has an id, a title, the Markdown body, a pinned flag and an updated number. We do not call Date.now() in the reducer (reducers must be pure, and React may call them twice in development), so the state carries its own clock: every change increments it and stamps the note. In a real app you would create the timestamp in the event handler and pass it in the action.

Which things are not in this state? The selected note id is UI state kept with useState in the app component. Storing the selected note object would be a mistake: after an edit, the stored copy would be stale. Store the id and look the note up during render, as in choosing state structure.

The editor edits the note directly: each keystroke dispatches an edited action with the changed field. That is a controlled input whose value comes straight from the store, so there is no separate draft state to synchronise. The preview next to it re-renders from the same body.

Stage 2: note list, editor and live preview

Look at handleAdd. It dispatches, then selects state.nextId. That works because state in this render still holds the counter value the reducer is about to use, and the new note receives exactly that id. It is a small coupling worth knowing about; if it bothers you, generate the id in the handler and pass it in the action (dispatch({ type: 'added', id })), which also removes the id counter from the reducer.

Step 3: search and pinning are derived data

Search needs a query and a filtered list. The temptation is to keep a second array called filteredNotes in state and update it from two places. Do not. The query is state; the filtered list is a calculation that runs during render:

JavaScript
const needle = query.trim().toLowerCase();
const visible = state.notes
  .filter((note) => (note.title + ' ' + note.body).toLowerCase().includes(needle))
  .sort(/* pinned first, then newest */);

One more detail: .sort() mutates the array it is called on. After .filter() we already have a fresh array, so mutating it is harmless here. Calling state.notes.sort(...) directly would mutate state, which is a bug (objects and arrays in state); use toSorted or sort a copy.

Pinning is a one-field change with a new action, pinToggled. The sorting rule is "pinned notes first; among equals, the most recently updated first". Because updated is stamped on every edit, a note you just edited jumps to the top of its group, a typical notes-app behaviour that costs us nothing: no re-ordering code, just the sort.

Do you need useMemo for the filtered list? Not at this size. Filtering a few hundred short strings takes a fraction of a millisecond, much less than the work React does anyway. Reach for useMemo only after profiling shows the list is slow, or when the list is very large.

Stage 3: search, pin and a sorted list

Search for bread: two notes match because the word is in their bodies, and the counter reads "2 of 4 notes". Search for trip and the matching part of the title is highlighted with <mark> (an element, not an HTML string). Search for zzz and you get the "No notes match" message. Clear the search, pin "Trip ideas", and it jumps to the top group; edit "Groceries" and it rises above other unpinned notes.

To keep this stage short the preview here is a compact version of the renderer from step 1 (headings, bold, italic, code). Your finished app should use the complete one.

Step 4: persistence, simulated

A notes app that forgets your notes on reload is not a notes app. In a real browser the standard tool is localStorage: a key/value store that holds strings. This is the code you would write in a normal project (read-only, because the sandbox of our editor blocks storage):

JSX
// Real browser code (not runnable in this editor)
function loadState() {
  try {
    const raw = localStorage.getItem('notes-v1');
    return raw ? JSON.parse(raw) : initialState;
  } catch {
    return initialState; // storage blocked or JSON corrupted
  }
}

const [state, dispatch] = useReducer(notesReducer, undefined, loadState);

useEffect(() => {
  localStorage.setItem('notes-v1', JSON.stringify(state));
}, [state]);

Three things deserve attention:

  • Lazy initial state. useReducer(reducer, undefined, loadState) calls loadState once, when the component mounts. Writing useReducer(reducer, loadState()) would read and parse storage on every render.
  • try/catch. Storage can be disabled, full, or contain damaged JSON. Always fall back to defaults.
  • Version in the key. notes-v1 lets a future release change the shape and ignore (or migrate) old data.

Saving is a classic Effect: it synchronizes React state with something outside React. Writing on every keystroke is wasteful, so the version below debounces the save with the same cleanup pattern as the search project (project: search): a short timer that each new change cancels.

In our sandbox we replace localStorage with a tiny in-memory object that has the same getItem and setItem methods. To prove persistence works, the app has a Simulate reload button that remounts the whole NotesApp by changing its key: all React state is thrown away and rebuilt from the "storage". We also derive the "Saved" indicator elegantly: after a save we remember the exact state object that was written, and the app is saved when savedState === state.

Stage 4: auto-save and reload with fake storage

Change a title, wait until the status says "All changes saved", then press the reload button: the edited note comes back. If you press reload before the 300 ms timer fires, the edit is lost, because the pending save was cancelled with the unmounted component. Real apps solve that with a beforeunload or pagehide listener that saves immediately, or by saving on every change when the data is small. That trade-off between write frequency and data loss is a design decision, not a React feature.

The console records storage empty, using defaults on the first load and loaded saved notes after a reload, so you can verify that the lazy initializer reads from storage.

Ideas to extend it

  • Tags stored as an array on each note, with a tag filter combined with the text query.
  • Undo by keeping a short history of states, as the Tic-Tac-Toe project does (project: tic-tac-toe).
  • Debounced search for thousands of notes, using the hook from the search project.
  • Export the current note as a file through a Blob URL, and import by reading a file input (uncontrolled and file forms).
  • Sync across tabs with the storage event, or move the data to a server and treat the browser as a cache (caching and server state).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does the Markdown renderer return React elements instead of an HTML string?

    Text that goes through JSX is always escaped. An HTML string would have to be injected with dangerouslySetInnerHTML, and any missed case would become a cross-site scripting hole.
  2. 2. The app stores selectedId rather than the selected note object. Why?

    Duplicating data in state means two copies that must stay in sync. Keeping only the id and finding the note during render guarantees you see the latest version.
  3. 3. Where does the filtered and sorted list of notes belong?

    It can be calculated from existing state, so storing it would only add a way for the two to disagree. Calculate it in render; use useMemo only if profiling shows it is slow.
  4. 4. What does useReducer(notesReducer, undefined, loadState) do differently from useReducer(notesReducer, loadState())?

    The third argument is a lazy initializer that React calls once. loadState() written directly runs on every render, even though only the first result is used.
  5. 5. How does the app know whether the latest changes are saved?

    After a save, the exact state object that was written is remembered. Because the reducer returns a new object for every change, savedState === state is true only when nothing changed since the last save.

Summary

  • Convert Markdown to blocks first, then render blocks as JSX; React's escaping keeps user text inert, and unsafe link targets (like javascript:) must be refused explicitly.
  • Keep minimal state: the notes in a reducer, the selected id, and the search text. Look up the selected note and compute the visible, sorted list during render.
  • Never mutate state when sorting or filtering: work on a copy (filter already returns one; use toSorted otherwise).
  • Make reducers pure by keeping counters such as nextId and a clock in the state, or by creating ids and timestamps in handlers.
  • Persist with a lazy initializer plus an Effect that saves, debounced with a cleanup; always wrap storage in try/catch and version the key.
  • Remounting with a changed key is a quick way to test that state really survives a reload.

Next: Project: Stopwatch and Countdown Timer