Step-by-Step Tutorial
TechnicalBeginner
Comprehensive tutorial with code examples, screenshots, and troubleshooting tips
#tutorial#guide#howto#technical#education
Created by md2x team•November 2, 2025
Get Started with This Example
Markdown Source
input.md
# Getting Started with React Hooks
**A Step-by-Step Tutorial for Beginners**
---
## Introduction
React Hooks revolutionized how we write React components. In this tutorial, you'll learn the fundamentals of Hooks and build a real-world todo list application.
**Prerequisites:**
- Basic JavaScript knowledge
- Familiarity with React components (class or functional)
- Node.js installed (v14+)
**Time to Complete:** 45 minutes
---
## Step 1: Project Setup
Create a new React project:
\`\`\`bash
npx create-react-app todo-app
cd todo-app
npm start
\`\`\`
Your app should open at `http://localhost:3000`.
---
## Step 2: Understanding useState
The `useState` Hook lets you add state to functional components.
**Create** `src/Counter.js`:
\`\`\`jsx
import { useState } from 'react'
function Counter() {
// Declare state variable
const [count, setCount] = useState(0)
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>
Increment
</button>
</div>
)
}
export default Counter
\`\`\`
**Key Concepts:**
- `useState(0)` initializes state with value `0`
- Returns array: `[currentValue, updateFunction]`
- Calling `setCount()` triggers re-render
---
## Step 3: Building the Todo List
**Create** `src/TodoList.js`:
\`\`\`jsx
import { useState } from 'react'
function TodoList() {
const [todos, setTodos] = useState([])
const [input, setInput] = useState('')
const addTodo = () => {
if (input.trim()) {
setTodos([...todos, { id: Date.now(), text: input, done: false }])
setInput('')
}
}
const toggleTodo = (id) => {
setTodos(todos.map(todo =>
todo.id === id ? { ...todo, done: !todo.done } : todo
))
}
const deleteTodo = (id) => {
setTodos(todos.filter(todo => todo.id !== id))
}
return (
<div>
<h1>Todo List</h1>
<input
value={input}
onChange={(e) => setInput(e.target.value)}
onKeyPress={(e) => e.key === 'Enter' && addTodo()}
placeholder="Add a task..."
/>
<button onClick={addTodo}>Add</button>
<ul>
{todos.map(todo => (
<li key={todo.id}>
<input
type="checkbox"
checked={todo.done}
onChange={() => toggleTodo(todo.id)}
/>
<span style={{ textDecoration: todo.done ? 'line-through' : 'none' }}>
{todo.text}
</span>
<button onClick={() => deleteTodo(todo.id)}>Delete</button>
</li>
))}
</ul>
</div>
)
}
export default TodoList
\`\`\`
---
## Step 4: Understanding useEffect
The `useEffect` Hook handles side effects (API calls, subscriptions, DOM updates).
**Add localStorage persistence:**
\`\`\`jsx
import { useState, useEffect } from 'react'
function TodoList() {
const [todos, setTodos] = useState(() => {
// Load from localStorage on initial render
const saved = localStorage.getItem('todos')
return saved ? JSON.parse(saved) : []
})
// Save to localStorage whenever todos change
useEffect(() => {
localStorage.setItem('todos', JSON.stringify(todos))
}, [todos]) // Dependency array: run when todos changes
// ... rest of component
}
\`\`\`
**useEffect Patterns:**
1. **Run once on mount:**
\`\`\`jsx
useEffect(() => {
console.log('Component mounted')
}, []) // Empty array = run once
\`\`\`
2. **Run on specific changes:**
\`\`\`jsx
useEffect(() => {
console.log('Count changed:', count)
}, [count]) // Run when count changes
\`\`\`
3. **Cleanup function:**
\`\`\`jsx
useEffect(() => {
const timer = setInterval(() => console.log('tick'), 1000)
return () => clearInterval(timer) // Cleanup
}, [])
\`\`\`
---
## Step 5: Custom Hooks
Extract reusable logic into custom Hooks.
**Create** `src/useLocalStorage.js`:
\`\`\`jsx
import { useState, useEffect } from 'react'
function useLocalStorage(key, initialValue) {
const [value, setValue] = useState(() => {
const saved = localStorage.getItem(key)
return saved ? JSON.parse(saved) : initialValue
})
useEffect(() => {
localStorage.setItem(key, JSON.stringify(value))
}, [key, value])
return [value, setValue]
}
export default useLocalStorage
\`\`\`
**Use it in TodoList:**
\`\`\`jsx
import useLocalStorage from './useLocalStorage'
function TodoList() {
const [todos, setTodos] = useLocalStorage('todos', [])
// ... rest of component
}
\`\`\`
---
## Step 6: Styling
**Add** `src/TodoList.css`:
\`\`\`css
.todo-container {
max-width: 600px;
margin: 50px auto;
padding: 20px;
background: white;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}
.todo-input {
width: 70%;
padding: 10px;
border: 2px solid #ddd;
border-radius: 4px;
font-size: 16px;
}
.todo-button {
padding: 10px 20px;
margin-left: 10px;
background: #007bff;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
.todo-item {
padding: 10px;
border-bottom: 1px solid #eee;
display: flex;
align-items: center;
gap: 10px;
}
\`\`\`
---
## Troubleshooting
**Issue:** Component not re-rendering
- ✅ Make sure you're calling the setter function (`setCount`, not `count = newValue`)
- ✅ Don't mutate state directly (use spread operator or `Array.map()`)
**Issue:** useEffect running infinitely
- ✅ Check dependency array
- ✅ Avoid object/array dependencies (use primitive values)
**Issue:** "Hooks can only be called inside function components"
- ✅ Don't call Hooks in loops, conditions, or nested functions
- ✅ Always call Hooks at the top level of your component
---
## Next Steps
🎯 **Challenges:**
1. Add categories/tags to todos
2. Implement filtering (all/active/completed)
3. Add due dates with date picker
4. Create a dark mode toggle
📚 **Learn More:**
- [React Hooks Documentation](https://react.dev/reference/react)
- [useReducer for Complex State](https://react.dev/reference/react/useReducer)
- [React Query for Data Fetching](https://tanstack.com/query)
---
## Conclusion
You've learned:
- ✅ How to use `useState` for state management
- ✅ How to use `useEffect` for side effects
- ✅ How to create custom Hooks
- ✅ How to build a practical todo app
**Full code:** [GitHub Repository](https://github.com/example/react-hooks-tutorial)
---
**Questions?** Leave a comment or reach out on Twitter [@alexdev](https://twitter.com)
307 lines • 6448 characters
PDF Output
output.pdf

Page 1 of 1 • Click image to zoom in
CSS Styling
style.css
/* Tutorial Style - Educational and structured */
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&family=JetBrains+Mono&display=swap');
body {
font-family: 'Inter', sans-serif;
font-size: 10.5pt;
line-height: 1.7;
color: #1f2937;
max-width: 7.5in;
margin: 0.75in auto;
}
h1 {
font-size: 26pt;
font-weight: 700;
color: #1e3a8a;
margin: 0 0 0.08in 0;
line-height: 1.2;
}
h1 + p {
font-size: 12pt;
font-weight: 600;
color: #4b5563;
margin: 0 0 0.15in 0;
}
hr {
border: none;
border-top: 2px solid #dbeafe;
margin: 0.2in 0;
}
h2 {
font-size: 16pt;
font-weight: 700;
color: #1e40af;
margin: 0.25in 0 0.12in 0;
padding: 0.08in;
background: #eff6ff;
border-left: 4px solid #3b82f6;
}
h3 {
font-size: 13pt;
font-weight: 600;
color: #374151;
margin: 0.15in 0 0.08in 0;
}
p {
margin: 0.08in 0;
}
code {
font-family: 'JetBrains Mono', monospace;
background: #f3f4f6;
padding: 0.02in 0.05in;
border-radius: 3px;
font-size: 9.5pt;
color: #dc2626;
}
pre {
background: #1f2937;
color: #f3f4f6;
padding: 0.12in;
border-radius: 6px;
overflow-x: auto;
margin: 0.12in 0;
font-family: 'JetBrains Mono', monospace;
font-size: 9pt;
border: 2px solid #3b82f6;
}
pre code {
background: none;
color: #f3f4f6;
padding: 0;
}
ul, ol {
margin: 0.08in 0;
padding-left: 0.3in;
}
ul li::marker {
color: #3b82f6;
}
strong {
font-weight: 700;
color: #1e40af;
}
blockquote {
background: #fef3c7;
border-left: 4px solid #f59e0b;
padding: 0.1in 0.15in;
margin: 0.12in 0.2in;
font-size: 10pt;
}
a {
color: #2563eb;
text-decoration: none;
}