React Components and JSX
Two Types of Components
Functional Components are JavaScript functions returning JSX. With React Hooks (16.8+), they manage state and side effects, making them the modern standard.
Class Components extend React.Component with a render() method. Feature-complete but more verbose; functional components are preferred.
// Functional component (modern, preferred)
function Greeting({ name }) {
return <h1>Hello, {name}</h1>;
}
// Class component (legacy)
class Greeting extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
JSX and createElement
JSX is syntactic sugar that compiles to React.createElement() calls:
// JSX
<div className="box">Hello</div>
// Compiles to
React.createElement('div', { className: 'box' }, 'Hello')
Modern React (17+) uses an optimized JSX transform eliminating the need to import React in every file.
JSX Rules
// ✅ Use className, not class
<div className="container">
// ✅ Self-close empty elements
<input type="text" />
<br />
// ✅ Single root element (or Fragment)
<>
<h1>Title</h1>
<p>Text</p>
</>
// ✅ Embed expressions with {}
<p>{user.name}</p>
<p>{isLoggedIn ? 'Welcome' : 'Please login'}</p>
Keys in Lists
Always use stable, unique identifiers as keys — never array indices:
// ❌ Bad: index keys break when list reorders
{items.map((item, index) => <li key={index}>{item.name}</li>)}
// ✅ Good: stable unique ID
{items.map(item => <li key={item.id}>{item.name}</li>)}
Index keys cause performance degradation during reordering since React can't properly track component identity.
Effect Cleanup
Always return cleanup functions from useEffect to prevent memory leaks:
useEffect(() => {
const ws = new WebSocket(url);
// ...
return () => ws.close(); // Cleanup on unmount
}, [url]);
Functional vs Class — Key Differences
| Aspect | Functional | Class |
|---|---|---|
| State | useState | this.state |
| Lifecycle | useEffect | Lifecycle methods |
this binding | Not needed | Required |
| Memory | Slightly less | Slightly more |
| Reusability | Custom hooks | HOCs / render props |
Content from Frontend-Master-Prep-Series — 03-react