Context API Implementation
Scenario
You are tasked with building a functional Todo application. Instead of relying on prop drilling or a complex third-party state management library for this scale, you will leverage React’s Context API to manage various aspects of the application’s state. This includes managing the list of todos, current visibility filters, and a simple theme.
This lab will provide practical experience in designing multiple contexts, implementing providers, consuming context values in components, and handling more involved state updates. You will also explore basic persistence and optimization considerations with Context.
Learning Objectives
Upon successful completion of this lab, you will be able to:
- Design and implement multiple, independent contexts for different pieces of global state.
- Create and use Context Providers to make state and dispatch functions available throughout the component tree.
- Consume context values and functions in components using the
useContext
hook. - Manage complex state (e.g., an array of objects, filter states) using
useState
oruseReducer
within context providers. - Implement features requiring interaction between different contexts (e.g., filtering todos).
- Add a persistence layer to a Context-based application (e.g., using
localStorage
). - Understand basic performance considerations when working with Context API.
Project Requirements
Build a Todo application with the following features, primarily using the Context API for state management.
1. Core Todo Management (TodoContext
)
- State: An array of todo items. Each todo item should have at least:
id
: A unique identifier (string or number).text
: The content of the todo (string).completed
: A boolean indicating if the todo is completed.
- Actions (exposed via context):
addTodo(text: string)
: Adds a new todo item to the list.toggleTodo(id: string | number)
: Toggles thecompleted
status of a todo item.deleteTodo(id: string | number)
: Removes a todo item from the list.editTodo(id: string | number, newText: string)
: Edits the text of an existing todo item.clearCompleted()
: Removes all completed todos.
- Components:
TodoInput
: An input field to add new todos.TodoList
: Displays the list of todo items.TodoItem
: Represents a single todo item, allowing interaction (toggle, delete, edit).
2. Visibility Filters (FilterContext
)
- State: The current visibility filter. Possible values: ‘all’, ‘active’, ‘completed’.
- Actions (exposed via context):
setFilter(filter: string)
: Sets the current filter.
- Functionality:
- The
TodoList
should display todos based on the currently active filter fromFilterContext
. FilterButtons
: A component that displays buttons to change the current filter.
- The
3. Theme Switching (ThemeContext
)
- State: The current theme. Possible values: ‘light’, ‘dark’.
- Actions (exposed via context):
toggleTheme()
: Switches between ‘light’ and ‘dark’ themes.
- Functionality:
- The application should visually change based on the selected theme (e.g., background colors, text colors). Apply theme changes to the main app container and ideally a few key components.
ThemeToggleButton
: A button to toggle the theme.
4. Persistence Layer
- Functionality:
- The state of the todos (from
TodoContext
) and the current theme (fromThemeContext
) should be persisted tolocalStorage
. - When the application loads, it should attempt to rehydrate these states from
localStorage
. - Updates to todos or theme should automatically update
localStorage
.
- The state of the todos (from
Example Solution
Todo App (Context API)
No todos yet! Add one above.
Implementation Guidelines
- State Management within Contexts: You can use
useState
for simpler contexts (likeFilterContext
orThemeContext
). ForTodoContext
, consider usinguseReducer
as it involves more complex state transitions, thoughuseState
is also acceptable if managed well. - Provider Nesting: Wrap your main application component with the necessary context providers. You might create a root provider component (e.g.,
AppProviders
) to keep yourApp.tsx
clean. - TypeScript (Optional but Recommended): Define types/interfaces for your todo items, context values, and props.
- Optimization: While not the primary focus, think about memoizing context values (using
useMemo
for objects/arrays,useCallback
for functions) to prevent unnecessary re-renders of consuming components. This is especially relevant for the persistence layer updates.
Submission
Submit your project on Canvas via a GitHub link that includes all necessary files for this lab. Ensure your contexts, providers, and the complete Todo application are included and functional.
Grading Rubric
Your submission will be evaluated based on the following criteria.
Criteria | Excellent | Good | Fair | Needs Improvement |
---|---|---|---|---|
Context Design & Provider Setup ( TodoContext , FilterContext , ThemeContext correctly defined and provided) | 15-13 pts • All contexts clearly defined with appropriate default values. • Providers correctly wrap the application, making context values accessible. • TypeScript types (if used) are accurate and comprehensive. | 12-10 pts • Contexts are defined and providers are set up mostly correctly. • Minor issues in default values or provider placement. • Basic TypeScript types (if used) are present. | 9-7 pts • Some contexts are missing or incorrectly set up. • Provider setup might be incomplete or flawed. • TypeScript types (if used) are minimal or have errors. | 6-0 pts • Contexts and Providers are largely missing or non-functional. • Core setup requirements not met. |
State Management & Reducers/Updaters (State logic for todos, filters, and theme within contexts) | 15-13 pts • All state update logic (add, toggle, delete, edit todos; set filter; toggle theme) is robust and correct. • useReducer (if used for todos) is implemented effectively.• State is immutable. | 12-10 pts • Most state update logic is correct. • Minor bugs may exist in some state transitions. • State immutability is generally maintained. | 9-7 pts • Significant portions of state logic are missing or incorrect. • May directly mutate state. • Several actions might not work as expected. | 6-0 pts • State management logic is fundamentally flawed or largely missing for key features. |
Application Functionality & Component Integration (Todo app works as specified; components consume context correctly) | 15-13 pts • All features (CRUD, filtering, theme switching) work flawlessly. • Components correctly consume context values and dispatch actions. • UI is clear and reflects state accurately. | 12-10 pts • Most features work as expected. • Components consume context generally well, with minor issues. • UI mostly reflects state, some inconsistencies may exist. | 9-7 pts • Several core features are buggy or non-functional. • Context consumption is problematic in multiple components. • UI does not reliably reflect the application state. | 6-0 pts • Application is largely non-functional. • Components fail to integrate with contexts properly. |
Persistence Layer & Optimization (State persisted to localStorage ; basic optimization in context providers) | 5 pts • Todo and Theme states are correctly persisted to and rehydrated from localStorage .• useMemo /useCallback used appropriately in providers to stabilize context values. | 4 pts • Persistence is implemented for at least one major piece of state (e.g., todos). • Some attempt at context value memoization. | 3-2 pts • Persistence is attempted but buggy or incomplete. • Little to no context optimization. | 1-0 pts • Persistence and optimization attempts are missing or non-functional. |
Total Points Possible: 50