📘
Advanced React with TypeScript: Hooks and Context
Advanced
140 XP
55 min
Lesson Content
Advanced React TypeScript
Learn to type React hooks, context, and advanced patterns for production React applications.
Typed useState
const [user, setUser] = useState(null);
const [count, setCount] = useState(0); Typed useReducer
type State = { count: number };
type Action = { type: 'increment' } | { type: 'decrement' };
function reducer(state: State, action: Action): State {
switch (action.type) {
case 'increment':
return { count: state.count + 1 };
case 'decrement':
return { count: state.count - 1 };
}
}Typed Context
interface ThemeContextType {
theme: 'light' | 'dark';
toggleTheme: () => void;
}
const ThemeContext = createContext(undefined); Custom Hooks
function useLocalStorage(key: string, initialValue: T) {
const [value, setValue] = useState(() => {
const item = localStorage.getItem(key);
return item ? JSON.parse(item) : initialValue;
});
return [value, setValue] as [T, typeof setValue];
} Example Code
Practice typing React hooks (conceptual)
// React hooks with TypeScript (conceptual)
// Simulate useState pattern
function useState<T>(initial: T): [T, (value: T) => void] {
let state = initial;
const setState = (value: T) => { state = value; };
return [state, setState];
}
const [count, setCount] = useState<number>(0);
console.log(`Count: ${count}`);Expected Output:
Count: 0
Study Tips
- •Read the theory content thoroughly before practicing
- •Review the example code to understand key concepts
- •Proceed to the Practice tab when you're ready to code