
Fundamentals of React
React is a JavaScript library for building user interfaces, and understanding its fundamentals is crucial for developing efficient and interactive web applications. Key concepts include:
1. Components (Building Blocks)
React apps are made of components – reusable, self-contained pieces of UI.
Functional Component:
function Welcome() {
return <h1>Hello, React!</h1>;
}
Class Component (less common now):
class Welcome extends React.Component {
render() {
return <h1>Hello, React!</h1>;
}
}
2. JSX (JavaScript XML)
JSX lets you write HTML inside JavaScript. It’s easier to read and write UI code.
const element = <h2>This is JSX</h2>;
3. Props (Component Inputs)
Props are how you pass data to components.
function Greet(props) {
return <h1>Hello, {props.name}</h1>;
}
// Usage
<Greet name="MCS" />
4. State (Component Data)
useState() lets functional components have internal data that can change.
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<>
<p>{count}</p>
<button onClick={() => setCount(count + 1)}>+</button>
</>
);
}
5. Event Handling
React uses camelCase events like onClick, onChange, etc.
<button onClick={() => alert('Clicked!')}>Click Me</button>
6. Conditional Rendering
Use if
, ternary ? :
, or logical &&
to show UI conditionally.
{isLoggedIn ? <Dashboard /> : <Login />}
7. Lists and Keys
Use .map() to display lists and add a unique key prop.
const items = ['A', 'B', 'C'];
<ul>
{items.map((item, index) => <li key={index}>{item}</li>)}
</ul>
8. useEffect Hook (Side Effects)
useEffect() is used for things like fetching data, setting up listeners, etc.
useEffect(() => {
console.log('Component mounted!');
}, []);
9. Component Tree / Structure
React builds a tree of components — components can have parent/child relationships and communicate via props.
10. Virtual DOM
React creates a virtual copy of the DOM and updates it efficiently when changes occur — improving performance.
Summary Table
Concept | Purpose |
---|---|
JSX | HTML inside JavaScript |
Components | Reusable UI blocks |
Props | Data from parent |
State | Local data that can change |
Event Handling | Handle user interaction |
Lists & Keys | Render dynamic data with unique keys |
useEffect | Handle side effects |
Virtual DOM | Fast UI updates |
Comments
Add new comment