CodeBlanks Logo Icon CodeBlanks

Summary - Zustand

Write a theme store and connect it to two components.

Summary - Zustand

In this group you learned what Zustand is, how to write a store with create, and how to prevent unnecessary renders with shallow. Now it's time to combine them.

Typical flow: write a theme store with create; components read the theme with a selector; they change it with toggle. No provider needed.

In the next step you will write a complete theme flow.

Practice Theme toggle component

Complete the skeleton. Write a ThemeToggle component. Call useTheme with selector (s) => s.theme (get theme). Call useTheme with selector (s) => s.toggle (get toggle). Render <button onClick={toggle}>{theme}</button>. Add export default.

Starter code

App.jsx
import { useTheme } from './useTheme';

// Write ThemeToggle here

Sample solution

App.jsx
import { useTheme } from './useTheme';

function ThemeToggle() {
  const theme = useTheme((s) => s.theme);
  const toggle = useTheme((s) => s.toggle);
  return <button onClick={toggle}>{theme}</button>;
}

export default ThemeToggle;

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which topic was NOT covered in this group?

App.jsx
Three topics were covered; Provider was not.
  • Store with create
  • Using selectors
  • shallow comparison
  • Redux Provider Correct answer

Explanation: Redux Provider was not covered in this group.

2 toggle call

Question
const toggle = use____((s) => s.toggle);
Answer
const toggle = useTheme((s) => s.toggle);

Explanation: useTheme returns the store hook.

All lessons in Advanced