props & state
- plain js objects
- trigger render updates
- props → get passed to the component
- part of component configuration
- immutable
- state → managed within the component
- if a component needs to alter one of its attributes then it should be part of state, otherwise prop
- private, internal
- changes trigger re-render
- stateless components - only props and no state
- stateful components - both props + state
- responsible for client server communication
- processing data
- responding to user events
context
- global state for entire application
- props drilling problem - parent components have to drill down props all the way down to all children
- context provides alternative way to pass down data through component tree
light-dark theme switcher
Step 1: Implement ThemeContext.js
ThemeContext.js
import { createContext, useContext, useState } from "react";
const ThemeContext = createContext();
export const ThemeProvider = ({ children }) => {
const [theme, setTheme] = useState("light");
const toggleTheme = () => {
setTheme(prev => (prev === "light" ? "dark" : "light"));
};
return (
<ThemeContext.Provider value={{ theme, toggleTheme }}>
{children}
</ThemeContext.Provider>
);
};
export const useTheme = () => {
return useContext(ThemeContext);
};
What this does
- Creates a global
ThemeContext
- Stores the current theme (
light or dark)
- Exposes a
toggleTheme function