Core Concepts
🧩 Components
React components are reusable pieces of code that return JSX elements to describe what should appear on the screen.
import React from 'react';
function Welcome(props) {
return (
<h1>Hello, {props.name}!</h1>
);
}
export default Welcome;
function Welcome(props) {
return (
<h1>Hello, {props.name}!</h1>
);
}
export default Welcome;
📊 State
State is a way to store and manage data that changes over time within a component.
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
🎣 Hooks
Hooks allow you to use state and other React features without writing a class component.
import React, { useState, useEffect } from 'react';
function Timer() {
const [seconds, setSeconds] = useState(0);
useEffect(() => {
const interval = setInterval(() => {
setSeconds(prev => prev + 1);
}, 1000);
return () => clearInterval(interval);
}, []);
return <div>Timer: {seconds}s</div>;
}
function Timer() {
const [seconds, setSeconds] = useState(0);
useEffect(() => {
const interval = setInterval(() => {
setSeconds(prev => prev + 1);
}, 1000);
return () => clearInterval(interval);
}, []);
return <div>Timer: {seconds}s</div>;
}
Interactive Counter Component
This demonstrates how React components maintain their own state:
0
Todo List Example
Shows how to manage lists and state in React:
Learn React fundamentals
Build a project
Complete Component Example
A more complex example combining multiple concepts:
import React, { useState, useEffect } from 'react';
function UserProfile({ userId }) {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
fetchUser(userId).then(userData => {
setUser(userData);
setLoading(false);
});
}, [userId]);
if (loading) return <div>Loading...</div>;
return (
<div>
<h2>{user.name}</h2>
<p>Email: {user.email}</p>
<p>Role: {user.role}</p>
</div>
);
}
function UserProfile({ userId }) {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
fetchUser(userId).then(userData => {
setUser(userData);
setLoading(false);
});
}, [userId]);
if (loading) return <div>Loading...</div>;
return (
<div>
<h2>{user.name}</h2>
<p>Email: {user.email}</p>
<p>Role: {user.role}</p>
</div>
);
}