What is React?
React is a JavaScript library for building user interfaces, developed by Facebook. It allows you to create reusable UI components and manage application state efficiently. React uses a virtual DOM for optimal performance and supports both web and mobile platforms (React Native).
Why React?
- Declarative – Describe how your UI should look, React handles updates
- Component-Based – Build encapsulated components that manage their own state
- Learn Once, Write Anywhere – React DOM for web, React Native for mobile
- Huge Ecosystem – Rich libraries, tools, and community support
- Performance – Virtual DOM for efficient updates
Setting Up a React Project
Your First Component
JSX Explained
JSX (JavaScript XML) is a syntax extension that allows you to write HTML-like code in JavaScript. It gets compiled to regular JavaScript function calls.
Components: Props
Components: State (useState)
useEffect – Side Effects
Event Handling
Conditional Rendering
Rendering Lists
React Hooks Overview
| Hook | Purpose | Example |
|---|---|---|
| useState | Local state management | const [count, setCount] = useState(0) |
| useEffect | Side effects | useEffect(() => {}, []) |
| useContext | Access context | const theme = useContext(ThemeContext) |
| useReducer | Complex state logic | const [state, dispatch] = useReducer(reducer, initialState) |
| useCallback | Memoized functions | const memoized = useCallback(() => {}, [deps]) |
| useMemo | Memoized values | const memoized = useMemo(() => compute(), [deps]) |
| useRef | Mutable references | const inputRef = useRef(null) |
Component Communication
Best Practices
- Use functional components and hooks – Avoid class components in new code
- Keep components small and focused – Single responsibility principle
- Use meaningful names – Components, props, and state should be descriptive
- Lift state up – Share state by moving it to common ancestors
- Avoid direct state mutation – Always use setState functions
- Use keys in lists – Stable, unique, predictable IDs
- Memoize expensive computations – useMemo and useCallback
- Use React DevTools – Debug and profile your components
Common Mistakes
- Mutating state directly –
state.count++instead ofsetState({...state, count: state.count + 1}) - Calling hooks conditionally – Hooks must be called at the top level
- Missing dependency arrays – Causes stale closures and infinite loops
- Using index as key – Causes issues with reordering
- Forgetting to prevent default – Form submissions cause page reloads
Conclusion
React provides a powerful, component-based approach to building user interfaces. Start with components, props, and state, then gradually explore hooks, context, and advanced patterns. Practice building small apps to reinforce these concepts.