Advanced React Patterns
React offers many powerful patterns that can help you write cleaner, more maintainable code.
Custom Hooks
Custom hooks are a great way to extract component logic:
typescript
import { useState, useEffect } from 'react'
function useLocalStorage<T>(key: string, initialValue: T) {
const [storedValue, setStoredValue] = useState<T>(() => {
try {
const item = window.localStorage.getItem(key)
return item ? JSON.parse(item) : initialValue
} catch (error) {
return initialValue
}
})
const setValue = (value: T | ((val: T) => T)) => {
try {
const valueToStore = value instanceof Function ? value(storedValue) : value
setStoredValue(valueToStore)
window.localStorage.setItem(key, JSON.stringify(valueToStore))
} catch (error) {
console.log(error)
}
}
return [storedValue, setValue] as const
}Context Pattern
The Context API is perfect for sharing state across components:
tsx
import { createContext, useContext, ReactNode } from 'react'
interface ThemeContextType {
theme: 'light' | 'dark'
toggleTheme: () => void
}
const ThemeContext = createContext<ThemeContextType | undefined>(undefined)
export function ThemeProvider({ children }: { children: ReactNode }) {
const [theme, setTheme] = useState<'light' | 'dark'>('light')
const toggleTheme = () => {
setTheme(prev => prev === 'light' ? 'dark' : 'light')
}
return (
<ThemeContext.Provider value={{ theme, toggleTheme }}>
{children}
</ThemeContext.Provider>
)
}Key Takeaways
- Custom hooks promote reusability
- Context helps avoid prop drilling
- Always consider performance implications
- Keep components focused and single-purpose
These patterns will help you build better React applications!