React + Functional Programming
Combining component-based UI with functional programming principles.
What is Functional Programming in React?
Functional programming principles can enhance React applications by promoting immutability, pure functions, and composability. This approach helps create predictable, testable, and maintainable code.
Key Principles
- Immutability
- Pure Functions
- Higher-Order Components
- Recursion over Loops
// Functional component example const Button = ({ onClick, children }) => ( <button onClick={onClick} className="bg-blue-500 text-white px-4 py-2 rounded"> {children} </button> ); // Pure function for state management const getItemCount = (state) => state.items.length;
Why Combine React with Functional Programming?
Predictable State
Using immutable data and pure functions makes state transitions easier to reason about and reduces side effects.
Testability
Pure functions are easier to test in isolation with tools like Jest or React Testing Library.
Reusability
Functional components and higher-order components promote reusability across different parts of the application.
Maintainability
Separating business logic from UI logic using functional principles leads to cleaner, more maintainable code.
Practical Functional Patterns
1. Using Pure Components
React's functional components with hooks naturally align with functional programming concepts.
const Counter = () => { const [count, setCount] = useState(0); const increment = useCallback(() => setCount(c => c + 1), [setCount]); return ( <div> <div>{count}</div> <button onClick={increment}>+1</button> </div> ); };
2. Higher-Order Components
HOCs allow you to reuse component logic by wrapping components with additional functionality.
const withLoading = (WrappedComponent) => ({ loading, ...props }) => ( {loading ? <div>Loading...</div> : <WrappedComponent {...props} />} ); const EnhancedList = withLoading(List);
3. Functional Selectors
Creating pure functions that derive data from the state for easier testing and reuse.
const getTotalPrice = (state) => { return state.items.reduce((sum, item) => sum + item.price, 0); }; // Usage in React const totalPrice = useSelector(getTotalPrice);
Best Practices for Functional React
Avoid Side-Effects in Components
Use useEffect for side effects and keep logic in pure functions outside the component.
Immutability for State Updates
Always create new objects/array when updating state instead of mutating existing data.
Compose Logic with Custom Hooks
Extract reusable logic into custom hooks to maintain separation of concerns.
Pure Render with useCallback/useMemo
Prevent unnecessary re-renders by memoizing expensive calculations and callbacks.
Example: Custom Hook
const useFetch = (url) => { const [data, setData] = useState(null); const [loading, setLoading] = useState(true); useEffect(() => { fetch(url) .then(res => res.json()) .then(data => { setData(data); setLoading(false); }); }, [url]); return { data, loading }; };