⚛️ React Context API Demo
A comprehensive React application demonstrating the power and flexibility of React Context API for state management. Built with modern React, Vite, and TypeScript, this project showcases how to effectively manage global state without prop drilling.
✨ Features
- Global State Management - Manage application state using React Context API
- No Prop Drilling - Pass data through component tree without manually passing props
- Multiple Contexts - Demonstrates various context patterns and use cases
- Modern React - Built with React 18+ and functional components with hooks
- Lightning Fast - Powered by Vite for instant development and HMR
- TypeScript Support - Full TypeScript integration for better developer experience
- ESLint Integration - Code quality and consistency with ESLint rules
🛠️ Tech Stack
- Frontend: React 18+, TypeScript
- Build Tool: Vite
- State Management: React Context API
- Development: Hot Module Replacement (HMR)
- Code Quality: ESLint
- Package Manager: npm/yarn
🏗️ Project Structure
Context-API/
├── src/
│ ├── components/ # React components
│ ├── context/ # Context providers and consumers
│ ├── hooks/ # Custom hooks for context
│ ├── types/ # TypeScript type definitions
│ ├── utils/ # Utility functions
│ ├── App.tsx # Main App component
│ └── main.tsx # Application entry point
├── public/ # Static assets
├── index.html # HTML template
├── package.json # Dependencies and scripts
├── vite.config.ts # Vite configuration
└── tsconfig.json # TypeScript configuration
🚀 Getting Started
Prerequisites
- Node.js (v16 or higher)
- npm or yarn package manager
Installation
-
Clone the repository
git clone https://github.com/whomimohshukla/Context-API.git
cd Context-API
-
Install dependencies
npm install
# or
yarn install
-
Start the development server
npm run dev
# or
yarn dev
-
Open your browser
Navigate to http://localhost:5173 to see the application
🎯 Context API Patterns Demonstrated
1. Basic Context Usage
// Creating a context
const MyContext = createContext<ContextType | undefined>(undefined);
// Provider component
const MyProvider = ({ children }: { children: ReactNode }) => {
const [state, setState] = useState<StateType>(initialState);
return (
<MyContext.Provider value={{ state, setState }}>
{children}
</MyContext.Provider>
);
};
2. Custom Hook Pattern
// Custom hook for consuming context
const useMyContext = () => {
const context = useContext(MyContext);
if (!context) {
throw new Error('useMyContext must be used within MyProvider');
}
return context;
};
3. Multiple Context Providers
- Theme Context - Managing application theme (light/dark mode)
- User Context - Managing user authentication state
- Cart Context - Managing shopping cart state
- Notification Context - Managing global notifications
📋 Available Scripts
npm run dev - Start development server
npm run build - Build for production
npm run preview - Preview production build
npm run lint - Run ESLint
🔧 Configuration
Vite Configuration
The project uses Vite with the following plugins:
@vitejs/plugin-react - React support with Babel
@vitejs/plugin-react-swc - Alternative React support with SWC (faster)
ESLint Configuration
ESLint is configured with React-specific rules for code quality and consistency.
🌟 Key Features Explained
Context API Benefits
- Eliminates Prop Drilling - No need to pass props through multiple component levels
- Global State Management - Share state across distant components
- Performance Optimization - Components only re-render when consumed context values change
- Type Safety - Full TypeScript support for context values
Best Practices Implemented
- Custom hooks for context consumption
- Proper error handling for context usage
- Context composition for complex state management
- Memoization to prevent unnecessary re-renders
🎨 Example Usage
// App.tsx
function App() {
return (
<ThemeProvider>
<UserProvider>
<CartProvider>
<Header />
<MainContent />
<Footer />
</CartProvider>
</UserProvider>
</ThemeProvider>
);
}
// Component using context
function ProductCard({ product }: { product: Product }) {
const { addToCart } = useCart();
const { theme } = useTheme();
return (
<div className={`card ${theme}`}>
<h3>{product.name}</h3>
<button onClick={() => addToCart(product)}>
Add to Cart
</button>
</div>
);
}
📚 Learning Resources
🤝 Contributing
Contributions are welcome! Please feel free to submit a Pull Request. Here's how you can contribute:
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature)
- Commit your changes (
git commit -m 'Add some amazing feature')
- Push to the branch (
git push origin feature/amazing-feature)
- Open a Pull Request
📄 License
This project is open-source and available under the MIT License.
👨💻 Author
Whomimohshukla
🙏 Acknowledgments
- React team for the amazing Context API
- Vite team for the lightning-fast build tool
- Open-source community for inspiration and best practices
🐛 Issues & Support
If you encounter any issues or have questions:
- Check the existing issues on GitHub
- Create a new issue with detailed description
- Include steps to reproduce the problem
Created with ❤️ by Whomimohshukla
Happy coding! 🚀