4 Advanced React Concepts
4 Advanced React Concepts
md 2024-10-24
Objective: Understand the session's focus on advanced React topics, including state management with hooks
and routing with React Router.
Objective: Learn how to manage state using useState and useContext hooks.
Example:
// CounterComponent.jsx
import React, { useState } from "react";
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
};
Multi-File Example:
1/5
4_Advanced React Concepts.md 2024-10-24
// ItemContext.js
import React, { createContext, useState } from "react";
return (
<ItemContext.Provider value={{ items, addItem }}>
{children}
</ItemContext.Provider>
);
};
// ItemList.jsx
import React, { useContext } from "react";
import { ItemContext } from "./ItemContext";
return (
<div>
<h2>Item List</h2>
<ul>
{items.map((item, index) => (
<li key={index}>{item}</li>
))}
</ul>
</div>
);
};
2/5
4_Advanced React Concepts.md 2024-10-24
// AddItem.jsx
import React, { useState, useContext } from "react";
import { ItemContext } from "./ItemContext";
return (
<div>
<input
type="text"
value={newItem}
onChange={(e) => setNewItem(e.target.value)}
placeholder="Enter a new item"
/>
<button onClick={handleAddItem}>Add Item</button>
</div>
);
};
// App.jsx
import React from "react";
import { ItemProvider } from "./ItemContext";
import ItemList from "./ItemList";
import AddItem from "./AddItem";
3/5
4_Advanced React Concepts.md 2024-10-24
Key Components:
// App.jsx
import React from "react";
import { BrowserRouter as Router, Route, Routes, Link } from "react-router-dom";
import { ItemProvider } from "./ItemContext";
import ItemList from "./ItemList";
import AddItem from "./AddItem";
4/5
4_Advanced React Concepts.md 2024-10-24
</ItemProvider>
);
};
Objective: Apply the concepts by enhancing the application with routing and hooks.
Instructions:
State Management:
Coding Assignment:
5/5