diff --git a/docs/intro.md b/docs/intro.md
index 3d20a54..c0d9781 100644
--- a/docs/intro.md
+++ b/docs/intro.md
@@ -12,7 +12,7 @@ import TabItem from '@theme/TabItem';
Web development is the process of creating and maintaining websites and web applications using technologies like HTML, CSS, and JavaScript. It involves frontend (user interface) and backend (server-side logic) development to build interactive, functional web experiences.
-**Try our [Interactive Code Playground](/docs/web-development/playground) to practice your web development skills in real-time!**
+**Try our [Interactive Code Playground](/docs/code-playground-demo) to practice your web development skills in real-time!**
@@ -45,6 +45,7 @@ Web development is the process of creating and maintaining websites and web appl
User -> System: Explore Further
```
+
@@ -76,6 +77,7 @@ Web development is the process of creating and maintaining websites and web appl
User -> System: Explore Further
```
+
```mermaid
@@ -98,6 +100,7 @@ Web development is the process of creating and maintaining websites and web appl
User -> System: Explore Further
```
+
@@ -131,6 +134,7 @@ Generative AI refers to algorithms and models that create new content such as te
User -> System: Explore Further
```
+
@@ -158,6 +162,7 @@ Generative AI refers to algorithms and models that create new content such as te
User -> System: Explore Further
```
+
@@ -185,6 +190,7 @@ Generative AI refers to algorithms and models that create new content such as te
User -> System: Explore Further
```
+
@@ -224,6 +230,7 @@ Data structures organize and store data efficiently, while algorithms are step-b
User -> System: Explore Further
```
+
@@ -260,6 +267,7 @@ Data structures organize and store data efficiently, while algorithms are step-b
User -> System: Explore Further
```
+
@@ -284,6 +292,7 @@ Data structures organize and store data efficiently, while algorithms are step-b
User -> System: Explore Further
```
+
@@ -317,6 +326,7 @@ Blockchain development involves building decentralized applications and smart co
User -> System: Explore Further
```
+
@@ -344,6 +354,7 @@ Blockchain development involves building decentralized applications and smart co
User -> System: Explore Further
```
+
@@ -374,5 +385,6 @@ Blockchain development involves building decentralized applications and smart co
User -> System: Explore Further
```
+
diff --git a/docs/web-developement/reactjs/quiz.js b/docs/web-developement/reactjs/quiz.js
new file mode 100644
index 0000000..28f1821
--- /dev/null
+++ b/docs/web-developement/reactjs/quiz.js
@@ -0,0 +1,609 @@
+export const reactIntroQuestions = [
+ {
+ id: "react-intro-1",
+ question: "What is the purpose of useState in React?",
+ options: [
+ "To store routing info",
+ "To fetch data from an API",
+ "To manage component state",
+ "To define props",
+ ],
+ correctAnswer: "To manage component state",
+ explanation:
+ "'useState' is a React Hook used to manage local state inside a component.",
+ },
+ {
+ id: "react-intro-2",
+ question: "What does JSX stand for?",
+ options: [
+ "JavaScript XML",
+ "Java Syntax Extension",
+ "JavaScript Extension",
+ "Java Xtreme Syntax",
+ ],
+ correctAnswer: "JavaScript XML",
+ explanation:
+ "JSX allows you to write HTML-like syntax directly in JavaScript files.",
+ },
+ {
+ id: "react-intro-3",
+ question: "What is the virtual DOM in React?",
+ options: [
+ "A physical copy of the real DOM",
+ "A faster version of the browser DOM",
+ "A lightweight in-memory representation of the real DOM",
+ "A database for React elements",
+ ],
+ correctAnswer: "A lightweight in-memory representation of the real DOM",
+ explanation:
+ "The virtual DOM improves performance by minimizing direct DOM manipulations.",
+ },
+];
+
+export const reactBasicQuestions = [
+ {
+ id: "react-basic-1",
+ question: "What are props in React?",
+ options: [
+ "Mutable data that belongs to a component",
+ "Read-only data passed from parent to child components",
+ "A way to store component state",
+ "Functions that update component data",
+ ],
+ correctAnswer: "Read-only data passed from parent to child components",
+ explanation:
+ "Props are read-only properties passed from parent components to child components, making components reusable and helping data flow down the component tree.",
+ },
+ {
+ id: "ract-basic-2",
+ question: "Which statement is true about React state?",
+ options: [
+ "State is read-only and cannot be changed",
+ "State is passed from parent components",
+ "State is mutable data that triggers re-renders when changed",
+ "State can only be used in class components",
+ ],
+ correctAnswer:
+ "State is mutable data that triggers re-renders when changed",
+ explanation:
+ "State is internal, mutable data that belongs to a component. When state changes, React automatically re-renders the component to reflect the new state.",
+ },
+ {
+ id: "react-basic-3",
+ question: "What is the Virtual DOM in React?",
+ options: [
+ "A physical copy of the real DOM",
+ "A faster version of the browser DOM",
+ "A JavaScript representation of the actual DOM kept in memory",
+ "A database for storing React components",
+ ],
+ correctAnswer:
+ "A JavaScript representation of the actual DOM kept in memory",
+ explanation:
+ "The Virtual DOM is a lightweight JavaScript representation of the real DOM. React uses it to optimize performance by comparing virtual DOM trees and updating only the changed parts in the real DOM.",
+ },
+ {
+ id: "react-basic-4",
+ question: "What are the three main phases of a React component lifecycle?",
+ options: [
+ "Creation, Rendering, Destruction",
+ "Mounting, Updating, Unmounting",
+ "Initialize, Update, Terminate",
+ "Start, Process, End",
+ ],
+ correctAnswer: "Mounting, Updating, Unmounting",
+ explanation:
+ "React components go through three main lifecycle phases: Mounting (component is created and inserted into DOM), Updating (component re-renders due to prop/state changes), and Unmounting (component is removed from DOM).",
+ },
+ {
+ id: "react-basic-5",
+ question: "Why are class components considered legacy in modern React?",
+ options: [
+ "They are slower than functional components",
+ "They don't support JSX syntax",
+ "They have more verbose syntax and are harder to optimize",
+ "They can't use props or state",
+ ],
+ correctAnswer: "They have more verbose syntax and are harder to optimize",
+ explanation:
+ "Class components are considered legacy because they have more verbose syntax, are harder to optimize, have less intuitive lifecycle management, and are no longer actively developed. Functional components are now the recommended approach.",
+ },
+];
+
+export const reactHooksQuiz = [
+ {
+ id: "react-hooks-1",
+ question:
+ "What will be the initial state value when this component renders?",
+ codeSnippet: {
+ code: `function Counter() {
+ const [count, setCount] = useState(10);
+
+ return (
+
+
Count: {count}
+
+
+ );
+}`,
+ language: "jsx",
+ },
+ options: ["0", "10", "undefined", "null"],
+ correctAnswer: "10",
+ explanation:
+ "useState(10) initializes the count state with the value 10, so the initial render will display 'Count: 10'.",
+ },
+
+ {
+ id: "react-hooks-2",
+ question: "How many times will the useEffect run in this component?",
+ codeSnippet: {
+ code: `function MyComponent() {
+ const [name, setName] = useState('John');
+ const [age, setAge] = useState(25);
+
+ useEffect(() => {
+ console.log('Effect ran');
+ }, []);
+
+ return (
+
+
+
+
+ );
+}`,
+ language: "jsx",
+ },
+ options: [
+ "Every time name or age changes",
+ "Only once after initial render",
+ "Never runs",
+ "Twice - once for name, once for age",
+ ],
+ correctAnswer: "Only once after initial render",
+ explanation:
+ "The useEffect has an empty dependency array [], which means it runs only once after the initial render, regardless of state changes.",
+ },
+
+ {
+ id: "react-hooks-3",
+ question: "What is the primary purpose of useMemo hook?",
+ options: [
+ "To memorize user inputs",
+ "To cache expensive calculations and prevent unnecessary recalculations",
+ "To remember component state between renders",
+ "To create memoized components",
+ ],
+ correctAnswer:
+ "To cache expensive calculations and prevent unnecessary recalculations",
+ explanation:
+ "useMemo is used to memoize expensive calculations so they only run when their dependencies change, helping optimize performance by avoiding unnecessary recalculations on every render.",
+ },
+
+ {
+ id: "react-hooks-4",
+ question: "What's the difference between useMemo and useCallback?",
+ options: [
+ "There is no difference, they are aliases",
+ "useMemo memoizes values, useCallback memoizes functions",
+ "useMemo is for class components, useCallback is for functional components",
+ "useMemo is faster than useCallback",
+ ],
+ correctAnswer: "useMemo memoizes values, useCallback memoizes functions",
+ explanation:
+ "useMemo memoizes the result of a computation (values), while useCallback memoizes the function itself. useCallback is essentially useMemo for functions.",
+ },
+
+ {
+ id: "react-hooks-5",
+ question: "What will happen when the button is clicked in this code?",
+ codeSnippet: {
+ code: `function TodoApp() {
+ const [todos, setTodos] = useState(['Learn React', 'Build App']);
+
+ const addTodo = useCallback(() => {
+ setTodos(prev => [...prev, 'New Todo']);
+ }, []);
+
+ return (
+
+ {todos.map((todo, index) =>
{todo}
)}
+
+
+ );
+}`,
+ language: "jsx",
+ },
+ options: [
+ "Nothing happens",
+ "A new todo 'New Todo' is added to the list",
+ "All todos are replaced with 'New Todo'",
+ "An error occurs",
+ ],
+ correctAnswer: "A new todo 'New Todo' is added to the list",
+ explanation:
+ "The useCallback memoized function uses the functional update pattern with setTodos(prev => [...prev, 'New Todo']), which spreads the previous todos array and adds 'New Todo' at the end.",
+ },
+
+ {
+ id: "react-hooks-6",
+ question: "When should you use useReducer instead of useState?",
+ options: [
+ "Always, it's more modern",
+ "When you have complex state logic with multiple sub-values or actions",
+ "When you want better performance",
+ "Only in class components",
+ ],
+ correctAnswer:
+ "When you have complex state logic with multiple sub-values or actions",
+ explanation:
+ "useReducer is preferable when you have complex state logic involving multiple sub-values, when the next state depends on the previous one, or when you want more predictable state updates through actions.",
+ },
+
+ {
+ id: "react-hooks-7",
+ question: "What is the main benefit of React v18's useTransition hook?",
+ options: [
+ "It speeds up all state updates",
+ "It allows marking state updates as non-urgent to keep UI responsive",
+ "It automatically batches all state updates",
+ "It replaces useEffect for better performance",
+ ],
+ correctAnswer:
+ "It allows marking state updates as non-urgent to keep UI responsive",
+ explanation:
+ "useTransition allows you to mark state updates as non-urgent (transitions), letting React prioritize more urgent updates like user input, keeping the UI responsive during heavy computations.",
+ },
+
+ {
+ id: "react-hooks-8",
+ question: "What's wrong with this custom hook code?",
+ codeSnippet: {
+ code: `function useCounter(initialValue) {
+ if (initialValue < 0) {
+ return { count: 0, increment: () => {} };
+ }
+
+ const [count, setCount] = useState(initialValue);
+ const increment = () => setCount(prev => prev + 1);
+
+ return { count, increment };
+}`,
+ language: "jsx",
+ },
+ options: [
+ "Nothing is wrong with this code",
+ "useState is called conditionally, violating the Rules of Hooks",
+ "The function name should not start with 'use'",
+ "Custom hooks cannot return objects",
+ ],
+ correctAnswer:
+ "useState is called conditionally, violating the Rules of Hooks",
+ explanation:
+ "Hooks must always be called in the same order on every render. Calling useState conditionally violates the Rules of Hooks. The hook should call useState unconditionally and handle the logic differently, such as: const [count, setCount] = useState(initialValue < 0 ? 0 : initialValue);",
+ },
+];
+
+export const reactContextQuiz = [
+ {
+ id: "context-api-1",
+ question: "What is the primary purpose of React Context API?",
+ options: [
+ "To create reusable UI components",
+ "To manage component lifecycle methods",
+ "To share data across components without prop drilling",
+ "To handle form validations",
+ ],
+ correctAnswer: "To share data across components without prop drilling",
+ explanation:
+ "React Context API is designed to solve the 'prop drilling' problem by allowing you to share state and data across your component tree without having to pass props through every level of nested components.",
+ },
+ {
+ id: "context-api-2",
+ question: "What will be logged to the console when this component renders?",
+ codeSnippet: {
+ code: `const ThemeContext = createContext('light');
+
+function DisplayTheme() {
+ const theme = useContext(ThemeContext);
+ console.log('Current theme:', theme);
+ return
Theme: {theme}
;
+}
+
+function App() {
+ return (
+
+
+
+ );
+}`,
+ language: "jsx",
+ },
+ options: [
+ "Current theme: undefined",
+ "Current theme: light",
+ "Current theme: null",
+ "Nothing is logged, an error occurs",
+ ],
+ correctAnswer: "Current theme: light",
+ explanation:
+ "When no Provider is present in the component tree, useContext returns the default value provided to createContext(). In this case, 'light' was passed as the default value.",
+ },
+ {
+ id: "context-api-3",
+ question:
+ "Which hook is recommended for consuming Context values in functional components?",
+ options: ["useEffect", "useContext", "useState", "useReducer"],
+ correctAnswer: "useContext",
+ explanation:
+ "The useContext hook is the recommended way to consume Context values in functional components. It's cleaner and more intuitive than the Context.Consumer render prop pattern.",
+ },
+ {
+ id: "context-api-4",
+ question: "What happens when this button is clicked?",
+ codeSnippet: {
+ code: `const CountContext = createContext();
+
+function CountProvider({ children }) {
+ const [count, setCount] = useState(0);
+ return (
+
+ {children}
+
+ );
+}
+
+function Counter() {
+ const { count, setCount } = useContext(CountContext);
+ return (
+
+ );
+}`,
+ language: "jsx",
+ },
+ options: [
+ "The count increases by 1 and all consumers re-render",
+ "Only the Counter component re-renders",
+ "Nothing happens because Context is immutable",
+ "An error occurs because setCount is not a function",
+ ],
+ correctAnswer: "The count increases by 1 and all consumers re-render",
+ explanation:
+ "When the Context value changes (count is updated), React automatically re-renders all components that consume that Context. The Provider creates a new value object, triggering updates to all consumers.",
+ },
+ {
+ id: "context-api-5",
+ question:
+ "What is the main performance issue with this Context implementation?",
+ codeSnippet: {
+ code: `function UserProvider({ children }) {
+ const [user, setUser] = useState(null);
+
+ return (
+ setUser(userData),
+ logout: () => setUser(null)
+ }}>
+ {children}
+
+ );
+}`,
+ language: "jsx",
+ },
+ options: [
+ "The user state is not initialized properly",
+ "New object and functions are created on every render, causing unnecessary re-renders",
+ "The Context value is undefined",
+ "There are no performance issues with this code",
+ ],
+ correctAnswer:
+ "New object and functions are created on every render, causing unnecessary re-renders",
+ explanation:
+ "The value prop creates a new object with new function references on every render. This causes all Context consumers to re-render unnecessarily, even when the actual user data hasn't changed. The solution is to use useMemo and useCallback to stabilize references.",
+ },
+ {
+ id: "context-api-6",
+ question: "When should you avoid using Context API?",
+ options: [
+ "When you need to share data between many components",
+ "When data changes very frequently and performance is critical",
+ "When implementing global application state",
+ "When you want to avoid prop drilling",
+ ],
+ correctAnswer:
+ "When data changes very frequently and performance is critical",
+ explanation:
+ "Context API causes all consumers to re-render when the value changes. For frequently changing data, this can create performance issues. In such cases, consider alternatives like state management libraries (Redux, Zustand) or keeping state local to components.",
+ },
+ {
+ id: "context-api-7",
+ question:
+ "What is the benefit of creating custom hooks for Context consumption?",
+ options: [
+ "Custom hooks make components render faster",
+ "They provide better error handling and cleaner API for consumers",
+ "They automatically optimize Context performance",
+ "They are required by React to use Context",
+ ],
+ correctAnswer:
+ "They provide better error handling and cleaner API for consumers",
+ explanation:
+ "Custom hooks like 'useTheme' or 'useAuth' encapsulate the useContext call and can provide better error messages when used outside of a Provider. They also create a cleaner, more semantic API for consuming Context values and can include additional logic or derived values.",
+ },
+];
+
+export const reactHOCQuiz = [
+ {
+ id: "hoc-basic-1",
+ question: "What will be rendered when this HOC is used?",
+ codeSnippet: {
+ code: `const withGreeting = (WrappedComponent) => {
+ return (props) => {
+ return ;
+ };
+};
+
+const DisplayMessage = ({ message, greeting }) => {
+ return
",
+ explanation:
+ "The HOC checks the isVisible prop. When isVisible is false, it returns the fallback div instead of rendering the wrapped component. The Content component never receives the props in this case.",
+ },
+ {
+ id: "hoc-composition-4",
+ question: "What will be the final props received by BaseComponent?",
+ codeSnippet: {
+ code: `const withA = (Component) => (props) =>
+ ;
+
+const withB = (Component) => (props) =>
+ ;
+
+const BaseComponent = (props) => {
+ console.log(props);
+ return
Base
;
+};
+
+const Enhanced = withA(withB(BaseComponent));
+
+function App() {
+ return ;
+}`,
+ language: "jsx",
+ },
+ options: [
+ "{ original: 'test', a: 'valueA' }",
+ "{ original: 'test', b: 'valueB' }",
+ "{ original: 'test', a: 'valueA', b: 'valueB' }",
+ "{ a: 'valueA', b: 'valueB' }",
+ ],
+ correctAnswer: "{ original: 'test', a: 'valueA', b: 'valueB' }",
+ explanation:
+ "HOCs are composed from right to left. withB wraps BaseComponent first, adding prop 'b'. Then withA wraps the result, adding prop 'a'. All props are spread through, so BaseComponent receives the original prop plus both added props.",
+ },
+ {
+ id: "hoc-state-5",
+ question:
+ "How many times will 'Counter rendered' be logged when the button is clicked twice?",
+ codeSnippet: {
+ code: `const withCounter = (WrappedComponent) => {
+ return (props) => {
+ const [count, setCount] = useState(0);
+
+ return (
+ setCount(c => c + 1)}
+ />
+ );
+ };
+};
+
+const Counter = ({ count, increment }) => {
+ console.log('Counter rendered');
+ return (
+
+
Count: {count}
+
+
+ );
+};
+
+const EnhancedCounter = withCounter(Counter);
+
+`,
+ language: "jsx",
+ },
+ options: ["2 times", "3 times", "4 times", "6 times"],
+ correctAnswer: "3 times",
+ explanation:
+ "The Counter component renders: 1) Once on initial mount, 2) Once when count changes from 0 to 1 (first click), 3) Once when count changes from 1 to 2 (second click). Each state change in the HOC triggers a re-render of the wrapped component.",
+ },
+];
\ No newline at end of file
diff --git a/docs/web-developement/reactjs/react-0.md b/docs/web-developement/reactjs/react-0.md
index 1ef6083..2b06b41 100644
--- a/docs/web-developement/reactjs/react-0.md
+++ b/docs/web-developement/reactjs/react-0.md
@@ -5,7 +5,7 @@ title: Introduction to React
sidebar_label: React Introduction
---
-Hey, everyone! In this guide, we’re going to explore **React**, one of the most popular JavaScript libraries for building user interfaces. Developed and maintained by Facebook, React helps developers create fast, dynamic, and scalable web applications with ease. Let’s jump into what makes React so powerful and widely used!
+Hey, everyone! In this guide, we’re going to explore **React**, one of the most popular JavaScript libraries for building user interfaces. Developed and maintained by Facebook, React helps developers create fast, dynamic, and scalable web applications with ease. Let’s jump into what makes React so powerful and widely used!
---
@@ -14,6 +14,7 @@ Hey, everyone! In this guide, we’re going to explore **React**, one of the mo
**React** is a declarative, component-based JavaScript library used for building interactive UIs. It's especially great for building **single-page applications (SPAs)** where you need real-time updates and efficient rendering.
### Key Features:
+
- **Component-Based**: Break your UI into reusable pieces.
- **Virtual DOM**: Improves performance by updating only the parts of the UI that change.
- **Declarative**: Describe what the UI should look like, and React takes care of the rest.
@@ -39,7 +40,7 @@ React was first released in 2013 and powers major apps like Facebook, Instagram,
Here’s what a basic React component looks like:
```jsx
-import React from 'react';
+import React from "react";
function Greeting() {
return
Hello, React!
;
@@ -49,12 +50,13 @@ export default Greeting;
```
### Rendering to the DOM:
+
```jsx
-import React from 'react';
-import ReactDOM from 'react-dom/client';
-import Greeting from './Greeting';
+import React from "react";
+import ReactDOM from "react-dom/client";
+import Greeting from "./Greeting";
-const root = ReactDOM.createRoot(document.getElementById('root'));
+const root = ReactDOM.createRoot(document.getElementById("root"));
root.render();
```
@@ -79,6 +81,7 @@ const element =
Hello, world!
;
## 5. Components in React
### Functional Component:
+
```jsx
function Welcome(props) {
return
Hello, {props.name}
;
@@ -86,6 +89,7 @@ function Welcome(props) {
```
### Class Component:
+
```jsx
class Welcome extends React.Component {
render() {
@@ -101,12 +105,14 @@ Most modern React apps use **functional components** with **Hooks**.
## 6. Adding React to Your Project
### 6.1 Using CDN (Quick Start):
+
```html
```
### 6.2 Using Create React App:
+
```bash
npx create-react-app my-app
cd my-app
@@ -133,7 +139,6 @@ React makes building modern web interfaces intuitive and efficient. Whether you'
## 9. Quiz Time
import { Quiz } from '@site/src/components/Quiz';
-import quiz from './quiz.json';
+import {reactIntroQuestions} from './quiz.js';
-
----
+##
diff --git a/docs/web-developement/reactjs/react-1.md b/docs/web-developement/reactjs/react-1.md
new file mode 100644
index 0000000..d658f2d
--- /dev/null
+++ b/docs/web-developement/reactjs/react-1.md
@@ -0,0 +1,295 @@
+---
+id: introduction-to-react-basic
+sidebar_position: 2
+title: React Basic
+sidebar_label: React Basic
+---
+
+Hey, everyone! In this guide, we’re going to explore some of basic concepts of **React**, like component lifecycle, props, state, and what's difference between props and state. We'll also take brief look into class based components.
+
+## Table of Contents
+
+1. [Introduction to React](#introduction-to-react)
+2. [Props](#props)
+3. [State](#state)
+4. [Component Lifecycle](#component-lifecycle)
+5. [Virtual DOM](#virtual-dom)
+6. [Class Components (Legacy)](#class-components-legacy)
+7. [Best Practices](#best-practices)
+
+---
+
+## Introduction to React
+
+React is a JavaScript library for building user interfaces. It allows you to create reusable UI components and manage application state efficiently.
+
+### Key Concepts
+
+- **Components**: Building blocks of React applications
+- **JSX**: JavaScript XML syntax for writing React elements
+- **Declarative**: Describe what the UI should look like
+- **Component-based**: Build encapsulated components
+
+```jsx
+function Welcome() {
+ return
Hello, World!
;
+}
+```
+
+---
+
+## Props
+
+Props are how you pass data from parent to child components. They are read-only and make components reusable.
+
+### Basic Props
+
+```jsx
+function Greeting({ name, age }) {
+ return (
+
+
Hello, {name}!
+
Age: {age}
+
+ );
+}
+
+// Usage
+;
+```
+
+### Default Values
+
+```jsx
+function Button({ text = "Click me", color = "blue", onClick }) {
+ return (
+
+ );
+}
+```
+
+### Type Checking (Modern Approach)
+
+> **Note**: PropTypes were deprecated in April 2017 (v15.5.0). In React 19, we're removing the propType checks from the React package, and using them will be silently ignored. Use TypeScript or another type-checking solution instead.
+
+```tsx
+// TypeScript example (recommended)
+interface ButtonProps {
+ text?: string;
+ color?: string;
+ onClick: () => void;
+}
+
+function Button({ text = "Click me", color = "blue", onClick }: ButtonProps) {
+ return (
+
+ );
+}
+```
+
+---
+
+## State
+
+State is mutable data that belongs to a component. When state changes, React re-renders the component.
+
+### Key Characteristics
+
+- **Mutable**: Can be changed over time
+- **Local**: Belongs to the component that defines it
+- **Triggers Re-renders**: Updates cause component to re-render
+- **Asynchronous**: State updates may be batched
+
+For more detials on how we can manage componet state please check `useState` hook example in our React Hooks guide.
+
+### State vs Props
+
+| State | Props |
+| --------------------- | ------------------ |
+| Mutable | Immutable |
+| Internal to component | Passed from parent |
+| Triggers re-renders | Read-only |
+
+### Lifting State Up
+
+```jsx
+function App() {
+ let temperature = 0;
+
+ const setTemperature = (temp) => {
+ temperature = temp;
+ // Re-render happens here
+ };
+
+ return (
+
+
+
+
+ );
+}
+```
+
+---
+
+## Component Lifecycle
+
+Components go through three main phases: mounting, updating, and unmounting.
+
+### Lifecycle Phases
+
+1. **Mounting**: Component is created and inserted into DOM
+2. **Updating**: Component re-renders due to prop/state changes
+3. **Unmounting**: Component is removed from DOM
+
+### Common Use Cases
+
+```jsx
+// Conceptual lifecycle events
+function DataComponent() {
+ // On Mount: Fetch data, set up subscriptions
+ // On Update: Respond to prop changes, re-fetch data
+ // On Unmount: Clean up subscriptions, cancel requests
+
+ return
Component Content
;
+}
+```
+
+---
+
+## Virtual DOM
+
+The Virtual DOM is a JavaScript representation of the actual DOM that makes React fast and efficient.
+
+### How It Works
+
+1. **Initial Render**: React creates virtual DOM tree
+2. **State Change**: New virtual DOM tree is created
+3. **Diffing**: React compares old and new trees
+4. **Reconciliation**: Calculate minimum changes needed
+5. **Update**: Update only changed parts in real DOM
+
+### Example
+
+```jsx
+// When state changes, React:
+// 1. Creates new Virtual DOM tree
+// 2. Compares with previous tree
+// 3. Updates only changed elements in real DOM
+
+function TodoList({ todos }) {
+ return (
+
+ {todos.map((todo) => (
+
{todo.text}
+ ))}
+
+ );
+}
+```
+
+### Benefits
+
+- **Performance**: Minimizes expensive DOM operations
+- **Batch Updates**: Groups multiple changes together
+- **Predictable**: Makes UI updates more predictable
+- **Cross-browser**: Abstracts away browser differences
+
+---
+
+## Class Components (Legacy)
+
+> ⚠️ **Warning**: Class components are legacy. Use functional components for new projects.
+
+### Basic Class Component
+
+```jsx
+class Welcome extends Component {
+ render() {
+ return
;
+ }
+}
+```
+
+### Why Avoid Class Components
+
+- More verbose syntax
+- Harder to optimize
+- Less intuitive lifecycle management
+- Functional components are preferred
+
+---
+
+## Conclusion
+
+React's core concepts provide a solid foundation for building modern web applications:
+
+- **Props**: Read-only data passed between components
+- **State**: Mutable data that triggers re-renders
+- **Lifecycle**: Understanding component phases
+- **Virtual DOM**: React's optimization layer
+- **Modern Approach**: Prefer functional components
+
+---
+
+## Quiz Time
+
+import { Quiz } from '@site/src/components/Quiz';
+import {reactBasicQuestions} from './quiz.js';
+
+##
diff --git a/docs/web-developement/reactjs/react-2.md b/docs/web-developement/reactjs/react-2.md
new file mode 100644
index 0000000..c677998
--- /dev/null
+++ b/docs/web-developement/reactjs/react-2.md
@@ -0,0 +1,621 @@
+---
+id: introduction-to-react-hooks
+sidebar_position: 3
+title: React Hooks
+sidebar_label: React Hooks
+---
+
+Hey, everyone! In this guide, we’re diving into React Hooks—a powerful feature that lets you use state and other React features in your functional components. Introduced in React 16.8, Hooks make it easier than ever to write clean, reusable, and stateful logic without needing class components. Let’s learn what Hooks are and why they’ve become essential for modern React development!
+
+---
+
+## What are React Hooks?
+
+**Hooks** are special functions that let you “hook into” React state and lifecycle features from your functional components. Before Hooks, only class components could manage state and side effects, but Hooks bring these superpowers to functional components as well. Hooks also helps us in performing react lifecycle methods in functional components. We'll deep dive into that in later part of this doc.
+
+#### Key Features:
+
+- **Stateful logic in functions**: Use [useState](#usestate) and others directly in your component functions.
+- **Code reuse**: Easily share logic between components with custom Hooks.
+- **Cleaner code**: No need to refactor into class components to use state or lifecycle methods.
+- **Community standard**: Most of the new React are compnents are funtional component.
+
+:::tip Did You Know?
+Hooks were officially added to React in February 2019, changing how most React code is written today.
+:::
+
+---
+
+## Why Use Hooks?
+
+- Simplifies components—no need for classes for state or side effects.
+- Reusable logic through custom Hooks.
+- Excellent for separating UI from business logic.
+- Adds new capabilities like easily reacting to props/state changes.
+
+---
+
+## Few of widely used React Hooks
+
+Below are a few of the most widely used React Hooks. We'll deep dive into each Hook separately and also explore some of the new Hooks added recently in React v18 and v19:
+
+- [useState](#usestate)
+- [useEffect](#useeffect)
+- [useMemo](#usememo)
+- [useCallback](#usecallback)
+- [useReducer](#usereducer)
+
+---
+
+### useState
+
+Lets you add state to functional components. It returns a state variable and a function to update it, enabling components to remember and update values between renders.
+
+**Purpose:** Manage state in functional components
+
+**Syntax:**
+
+```javascript
+const [state, setState] = useState(initialValue);
+```
+
+**Example:**
+
+```javascript
+import { useState } from "react";
+
+function Counter() {
+ const [count, setCount] = useState(0);
+
+ return (
+
+
Count: {count}
+
+
+ );
+}
+```
+
+---
+
+### useEffect
+
+Used for performing side effects in functional components, such as data fetching, subscriptions, or manually changing the DOM. It combines the behavior of many class lifecycle methods like componentDidMount, componentDidUpdate, and componentWillUnmount.
+
+**Purpose:** Handle side effects and lifecycle events
+
+**Syntax:**
+
+```javascript
+useEffect(() => {
+ // Side effect logic
+ return () => {
+ // Cleanup (optional)
+ };
+}, [dependencies]); // Optional dependency array
+```
+
+**Examples:**
+
+```javascript
+import { useEffect, useState } from "react";
+
+function DataFetcher() {
+ const [data, setData] = useState(null);
+
+ // Run once on mount
+ useEffect(() => {
+ fetch("/api/data")
+ .then((response) => response.json())
+ .then(setData);
+ }, []); // Empty dependency array
+
+ // Run when data changes
+ useEffect(() => {
+ document.title = `Data: ${data?.name || "Loading"}`;
+ }, [data]); // Runs when 'data' changes
+
+ return
{data?.name}
;
+}
+```
+
+---
+
+### useMemo
+
+Optimizes expensive calculations by memoizing a value and recomputing it only when its dependencies change, improving performance by avoiding unnecessary recalculations.
+
+**Purpose:** Memoize expensive calculations
+
+**Syntax:**
+
+```javascript
+const memoizedValue = useMemo(() => {
+ return expensiveCalculation(a, b);
+}, [a, b]); // Dependencies
+```
+
+**Example:**
+
+```javascript
+import { useMemo, useState } from "react";
+
+function ExpensiveComponent({ items }) {
+ const [filter, setFilter] = useState("");
+
+ const filteredItems = useMemo(() => {
+ console.log("Filtering items..."); // Only runs when items/filter change
+ return items.filter((item) =>
+ item.name.toLowerCase().includes(filter.toLowerCase())
+ );
+ }, [items, filter]);
+
+ return (
+
+ );
+}
+```
+
+---
+
+### useCallback
+
+Returns a memoized version of a callback function that only changes if one of its dependencies changes. Useful to prevent unnecessary re-renders in child components that rely on stable function references.
+
+**Purpose:** Memoize functions to prevent unnecessary re-renders
+
+**Syntax:**
+
+```javascript
+const memoizedCallback = useCallback(() => {
+ // Function logic
+}, [dependencies]);
+```
+
+**Example:**
+
+```javascript
+import { useCallback, useState, memo } from "react";
+
+// Child component that only re-renders when props actually change
+const ChildComponent = memo(({ onButtonClick, value }) => {
+ console.log("Child rendered");
+ return ;
+});
+
+function ParentComponent() {
+ const [count, setCount] = useState(0);
+ const [name, setName] = useState("");
+
+ // Without useCallback, this function is recreated on every render
+ const handleClick = useCallback(() => {
+ setCount((prev) => prev + 1);
+ }, []); // No dependencies, so function never changes
+
+ return (
+
+ setName(e.target.value)} />
+
+
+ );
+}
+```
+
+---
+
+### useReducer
+
+An alternative to useState for managing complex state logic. It works like a reducer in Redux, allowing state transitions based on dispatched actions and a reducer function.
+
+**Purpose:** Manage complex state logic with actions
+
+**Syntax:**
+
+```javascript
+const [state, dispatch] = useReducer(reducer, initialState);
+
+function reducer(state, action) {
+ switch (action.type) {
+ case "ACTION_TYPE":
+ return newState;
+ default:
+ return state;
+ }
+}
+```
+
+**Example:**
+
+```javascript
+import { useReducer } from "react";
+
+// Reducer function
+function counterReducer(state, action) {
+ switch (action.type) {
+ case "increment":
+ return { count: state.count + 1 };
+ case "decrement":
+ return { count: state.count - 1 };
+ case "reset":
+ return { count: 0 };
+ case "set":
+ return { count: action.payload };
+ default:
+ return state;
+ }
+}
+
+function Counter() {
+ const [state, dispatch] = useReducer(counterReducer, { count: 0 });
+
+ return (
+
+ );
+}
+```
+
+---
+
+## Rules for Custom Hooks
+
+1. **Must start with `use`** - React convention
+2. **Only call hooks at the top level** - No conditions, loops, or nested functions
+3. **Only call from React functions** - Components or other custom hooks
+4. **Keep them pure** - Same inputs should return same outputs
+5. **Handle cleanup** - Use useEffect cleanup for subscriptions, timers, etc.
+
+---
+
+## Conclusion
+
+Hooks make React development more flexible and functional. They open the door for simpler code, stateful logic in functions, and easy logic sharing between components. Most new projects and libraries use Hooks as the standard way to build with React.
+
+## Quiz Time
+
+import { Quiz } from '@site/src/components/Quiz';
+import {reactHooksQuiz} from './quiz.js';
+
+##
diff --git a/docs/web-developement/reactjs/react-3.md b/docs/web-developement/reactjs/react-3.md
new file mode 100644
index 0000000..521d5ab
--- /dev/null
+++ b/docs/web-developement/reactjs/react-3.md
@@ -0,0 +1,475 @@
+---
+id: introduction-to-context-api
+sidebar_position: 4
+title: Context Api
+sidebar_label: Context Api
+---
+
+Hey, everyone! In this guide, we're diving deep into React Context API—a powerful built-in feature that lets you share state and data across your component tree without prop drilling. Introduced in React 16.3 and enhanced with Hooks in 16.8, Context API makes it easier than ever to manage global application state, themes, user authentication, and other cross-cutting concerns in your React applications. Let's explore what Context API is and why it's become essential for modern React development!
+
+---
+
+## Table of Contents
+
+- [Introduction](#introduction)
+- [When to Use Context](#when-to-use-context)
+- [Basic Concepts](#basic-concepts)
+- [Creating Context](#creating-context)
+- [Using Context](#using-context)
+- [Best Practices](#best-practices)
+- [Examples](#examples)
+
+---
+
+## Introduction
+
+The React Context API is a powerful feature that allows you to share data between components without having to pass props down through multiple levels of the component tree. It's designed to solve the "prop drilling" problem and provides a way to create global state that can be accessed by any component in your React application.
+
+Context is built into React and provides a clean, efficient way to manage state that needs to be accessible across many components at different nesting levels.
+
+---
+
+## When to Use Context
+
+Context is ideal for data that can be considered "global" for a tree of React components, such as:
+
+- **Theme data** (e.g., dark/light mode)
+- **User authentication status** and user information
+- **Language/localization preferences**
+- **Application settings and configuration**
+- **Shopping cart data in e-commerce apps**
+- **Current user preferences**
+
+### When NOT to Use Context
+
+- **Component-specific state** that only affects a single component
+- **Frequently changing data** that causes performance issues
+- **Simple parent-to-child communication** (use props instead)
+- **When you just want to avoid passing props through 2-3 levels** (prop drilling isn't always bad)
+
+---
+
+## Basic Concepts
+
+### 1. Context Object
+
+Created using `React.createContext()`, this object holds the shared data.
+
+### 2. Provider Component
+
+Wraps components that need access to the context data and provides the value.
+
+### 3. Consumer Component/Hook
+
+Components that read the context data using either `useContext` hook or Context.Consumer.
+
+## Creating Context
+
+### Step 1: Create the Context
+
+```javascript
+import { createContext } from "react";
+
+// Create context with default value
+const ThemeContext = createContext("light");
+
+// Or with no default value
+const UserContext = createContext();
+
+// With default object value
+const AppContext = createContext({
+ theme: "light",
+ user: null,
+ toggleTheme: () => {},
+});
+```
+
+### Step 2: Create a Provider Component
+
+```javascript
+import { createContext, useState } from "react";
+
+const ThemeContext = createContext();
+
+export const ThemeProvider = ({ children }) => {
+ const [theme, setTheme] = useState("light");
+
+ const toggleTheme = () => {
+ setTheme((prevTheme) => (prevTheme === "light" ? "dark" : "light"));
+ };
+
+ const value = {
+ theme,
+ toggleTheme,
+ };
+
+ return (
+ {children}
+ );
+};
+
+export default ThemeContext;
+```
+
+---
+
+## Using Context
+
+### Method 1: useContext Hook (Recommended)
+
+```javascript
+import { useContext } from "react";
+import ThemeContext from "./ThemeContext";
+
+const MyComponent = () => {
+ const { theme, toggleTheme } = useContext(ThemeContext);
+
+ return (
+
+ );
+};
+
+function App() {
+ return (
+
+
+
+ );
+}
+```
+
+## Quiz Time
+
+import { Quiz } from '@site/src/components/Quiz';
+import {reactContextQuiz} from './quiz.js';
+
+##
diff --git a/docs/web-developement/reactjs/react-4.md b/docs/web-developement/reactjs/react-4.md
new file mode 100644
index 0000000..f61bc49
--- /dev/null
+++ b/docs/web-developement/reactjs/react-4.md
@@ -0,0 +1,274 @@
+---
+id: introduction-to-hoc
+sidebar_position: 5
+title: Higher order components
+sidebar_label: Higher order components
+---
+
+Higher-Order Components (HOCs) are an advanced technique in React for reusing component logic. HOCs are not part of the React API per se, but rather a pattern that emerges from React's compositional nature.
+A Higher-Order Component is a function that takes a component and returns a new component with enhanced functionality.
+
+---
+
+## Table of Contents
+
+- [What is a Higher-Order Component?](#what-is-a-higher-order-component)
+- [Basic HOC Pattern](#basic-hoc-pattern)
+- [HOC Examples](#hoc-examples)
+- [Best Practices](#best-practices)
+- [Common Pitfalls](#common-pitfalls)
+- [HOCs vs Hooks](#hocs-vs-hooks)
+- [Conclusion](#conclusion)
+
+---
+
+## What is a Higher-Order Component?
+
+```javascript
+const EnhancedComponent = higherOrderComponent(WrappedComponent);
+```
+
+A HOC is a pure function with zero side-effects that:
+
+- Takes a React component as an argument
+- Returns a new React component
+- The returned component renders the original component with additional props or behavior
+
+## Basic HOC Pattern
+
+### Function Component HOC
+
+```javascript
+import React from "react";
+
+// Basic HOC structure
+const withEnhancement = (WrappedComponent) => {
+ return (props) => {
+ // Add logic here
+ const enhancedProps = {
+ ...props,
+ additionalProp: "enhanced value",
+ };
+
+ return ;
+ };
+};
+
+// Usage
+const MyComponent = ({ message, additionalProp }) => (
+
+ );
+ };
+};
+```
+
+---
+
+## Best Practices
+
+### 1. Use Display Names for Debugging
+
+```javascript
+const withAuth = (WrappedComponent) => {
+ const AuthenticatedComponent = (props) => {
+ // HOC logic here
+ return ;
+ };
+
+ // Set display name for better debugging
+ AuthenticatedComponent.displayName = `withAuth(${
+ WrappedComponent.displayName || WrappedComponent.name
+ })`;
+
+ return AuthenticatedComponent;
+};
+```
+
+### 2. Copy Static Methods
+
+```javascript
+import hoistNonReactStatics from "hoist-non-react-statics";
+
+const withEnhancement = (WrappedComponent) => {
+ const EnhancedComponent = (props) => {
+ return ;
+ };
+
+ // Copy static methods
+ hoistNonReactStatics(EnhancedComponent, WrappedComponent);
+
+ return EnhancedComponent;
+};
+```
+
+### 3. Don't Use HOCs Inside Render
+
+```javascript
+// ❌ Bad: Creates new component on every render
+const MyComponent = () => {
+ const EnhancedComponent = withAuth(SomeComponent);
+ return ;
+};
+
+// ✅ Good: Create enhanced component outside
+const EnhancedComponent = withAuth(SomeComponent);
+
+const MyComponent = () => {
+ return ;
+};
+```
+
+## HOCs vs Hooks
+
+With the introduction of React Hooks, many HOC patterns can be replaced with custom hooks:
+
+### HOC Pattern
+
+```javascript
+const withCounter = (WrappedComponent) => {
+ return (props) => {
+ const [count, setCount] = useState(0);
+ return (
+ setCount((c) => c + 1)}
+ />
+ );
+ };
+};
+```
+
+### Hook Pattern
+
+```javascript
+const useCounter = (initialValue = 0) => {
+ const [count, setCount] = useState(initialValue);
+ const increment = () => setCount((c) => c + 1);
+ return { count, increment };
+};
+
+// Usage in component
+const MyComponent = () => {
+ const { count, increment } = useCounter();
+ return ;
+};
+```
+
+### When to Use HOCs vs Hooks
+
+**Use HOCs when:**
+
+- You need to wrap components conditionally
+- Working with class components
+- Need to modify component behavior at the component level
+
+**Use Hooks when:**
+
+- Working with function components
+- Need to share stateful logic
+- Want more granular control over what gets shared
+
+## Conclusion
+
+Higher-Order Components are a powerful pattern for code reuse in React applications. While hooks have become the preferred method for sharing stateful logic in modern React applications, HOCs still have their place, especially when working with class components or when you need to conditionally wrap components.
+
+Remember to follow best practices, avoid common pitfalls, and consider whether a custom hook might be a better solution for your use case.
+
+---
+
+_This documentation serves as a comprehensive guide to React HOCs. For more React patterns and best practices, refer to the official React documentation._
+
+---
+
+## Quiz Time
+
+import { Quiz } from '@site/src/components/Quiz';
+import {reactHOCQuiz} from './quiz.js';
+
+##
diff --git a/docs/web-developemnt/reactjs/quiz.js b/docs/web-developemnt/reactjs/quiz.js
new file mode 100644
index 0000000..f58ba72
--- /dev/null
+++ b/docs/web-developemnt/reactjs/quiz.js
@@ -0,0 +1,609 @@
+export const reactIntroQuestions = [
+ {
+ id: "react-intro-1",
+ question: "What is the purpose of useState in React?",
+ options: [
+ "To store routing info",
+ "To fetch data from an API",
+ "To manage component state",
+ "To define props",
+ ],
+ correctAnswer: "To manage component state",
+ explanation:
+ "'useState' is a React Hook used to manage local state inside a component.",
+ },
+ {
+ id: "react-intro-2",
+ question: "What does JSX stand for?",
+ options: [
+ "JavaScript XML",
+ "Java Syntax Extension",
+ "JavaScript Extension",
+ "Java Xtreme Syntax",
+ ],
+ correctAnswer: "JavaScript XML",
+ explanation:
+ "JSX allows you to write HTML-like syntax directly in JavaScript files.",
+ },
+ {
+ id: "react-intro-3",
+ question: "What is the virtual DOM in React?",
+ options: [
+ "A physical copy of the real DOM",
+ "A faster version of the browser DOM",
+ "A lightweight in-memory representation of the real DOM",
+ "A database for React elements",
+ ],
+ correctAnswer: "A lightweight in-memory representation of the real DOM",
+ explanation:
+ "The virtual DOM improves performance by minimizing direct DOM manipulations.",
+ },
+];
+
+export const reactBasicQuestions = [
+ {
+ id: "react-basic-1",
+ question: "What are props in React?",
+ options: [
+ "Mutable data that belongs to a component",
+ "Read-only data passed from parent to child components",
+ "A way to store component state",
+ "Functions that update component data",
+ ],
+ correctAnswer: "Read-only data passed from parent to child components",
+ explanation:
+ "Props are read-only properties passed from parent components to child components, making components reusable and helping data flow down the component tree.",
+ },
+ {
+ id: "ract-basic-2",
+ question: "Which statement is true about React state?",
+ options: [
+ "State is read-only and cannot be changed",
+ "State is passed from parent components",
+ "State is mutable data that triggers re-renders when changed",
+ "State can only be used in class components",
+ ],
+ correctAnswer:
+ "State is mutable data that triggers re-renders when changed",
+ explanation:
+ "State is internal, mutable data that belongs to a component. When state changes, React automatically re-renders the component to reflect the new state.",
+ },
+ {
+ id: "react-basic-3",
+ question: "What is the Virtual DOM in React?",
+ options: [
+ "A physical copy of the real DOM",
+ "A faster version of the browser DOM",
+ "A JavaScript representation of the actual DOM kept in memory",
+ "A database for storing React components",
+ ],
+ correctAnswer:
+ "A JavaScript representation of the actual DOM kept in memory",
+ explanation:
+ "The Virtual DOM is a lightweight JavaScript representation of the real DOM. React uses it to optimize performance by comparing virtual DOM trees and updating only the changed parts in the real DOM.",
+ },
+ {
+ id: "react-basic-4",
+ question: "What are the three main phases of a React component lifecycle?",
+ options: [
+ "Creation, Rendering, Destruction",
+ "Mounting, Updating, Unmounting",
+ "Initialize, Update, Terminate",
+ "Start, Process, End",
+ ],
+ correctAnswer: "Mounting, Updating, Unmounting",
+ explanation:
+ "React components go through three main lifecycle phases: Mounting (component is created and inserted into DOM), Updating (component re-renders due to prop/state changes), and Unmounting (component is removed from DOM).",
+ },
+ {
+ id: "react-basic-5",
+ question: "Why are class components considered legacy in modern React?",
+ options: [
+ "They are slower than functional components",
+ "They don't support JSX syntax",
+ "They have more verbose syntax and are harder to optimize",
+ "They can't use props or state",
+ ],
+ correctAnswer: "They have more verbose syntax and are harder to optimize",
+ explanation:
+ "Class components are considered legacy because they have more verbose syntax, are harder to optimize, have less intuitive lifecycle management, and are no longer actively developed. Functional components are now the recommended approach.",
+ },
+];
+
+export const reactHooksQuiz = [
+ {
+ id: "react-hooks-1",
+ question:
+ "What will be the initial state value when this component renders?",
+ codeSnippet: {
+ code: `function Counter() {
+ const [count, setCount] = useState(10);
+
+ return (
+
+
Count: {count}
+
+
+ );
+}`,
+ language: "jsx",
+ },
+ options: ["0", "10", "undefined", "null"],
+ correctAnswer: "10",
+ explanation:
+ "useState(10) initializes the count state with the value 10, so the initial render will display 'Count: 10'.",
+ },
+
+ {
+ id: "react-hooks-2",
+ question: "How many times will the useEffect run in this component?",
+ codeSnippet: {
+ code: `function MyComponent() {
+ const [name, setName] = useState('John');
+ const [age, setAge] = useState(25);
+
+ useEffect(() => {
+ console.log('Effect ran');
+ }, []);
+
+ return (
+
+
+
+
+ );
+}`,
+ language: "jsx",
+ },
+ options: [
+ "Every time name or age changes",
+ "Only once after initial render",
+ "Never runs",
+ "Twice - once for name, once for age",
+ ],
+ correctAnswer: "Only once after initial render",
+ explanation:
+ "The useEffect has an empty dependency array [], which means it runs only once after the initial render, regardless of state changes.",
+ },
+
+ {
+ id: "react-hooks-3",
+ question: "What is the primary purpose of useMemo hook?",
+ options: [
+ "To memorize user inputs",
+ "To cache expensive calculations and prevent unnecessary recalculations",
+ "To remember component state between renders",
+ "To create memoized components",
+ ],
+ correctAnswer:
+ "To cache expensive calculations and prevent unnecessary recalculations",
+ explanation:
+ "useMemo is used to memoize expensive calculations so they only run when their dependencies change, helping optimize performance by avoiding unnecessary recalculations on every render.",
+ },
+
+ {
+ id: "react-hooks-4",
+ question: "What's the difference between useMemo and useCallback?",
+ options: [
+ "There is no difference, they are aliases",
+ "useMemo memoizes values, useCallback memoizes functions",
+ "useMemo is for class components, useCallback is for functional components",
+ "useMemo is faster than useCallback",
+ ],
+ correctAnswer: "useMemo memoizes values, useCallback memoizes functions",
+ explanation:
+ "useMemo memoizes the result of a computation (values), while useCallback memoizes the function itself. useCallback is essentially useMemo for functions.",
+ },
+
+ {
+ id: "react-hooks-5",
+ question: "What will happen when the button is clicked in this code?",
+ codeSnippet: {
+ code: `function TodoApp() {
+ const [todos, setTodos] = useState(['Learn React', 'Build App']);
+
+ const addTodo = useCallback(() => {
+ setTodos(prev => [...prev, 'New Todo']);
+ }, []);
+
+ return (
+
+ {todos.map((todo, index) =>
{todo}
)}
+
+
+ );
+}`,
+ language: "jsx",
+ },
+ options: [
+ "Nothing happens",
+ "A new todo 'New Todo' is added to the list",
+ "All todos are replaced with 'New Todo'",
+ "An error occurs",
+ ],
+ correctAnswer: "A new todo 'New Todo' is added to the list",
+ explanation:
+ "The useCallback memoized function uses the functional update pattern with setTodos(prev => [...prev, 'New Todo']), which spreads the previous todos array and adds 'New Todo' at the end.",
+ },
+
+ {
+ id: "react-hooks-6",
+ question: "When should you use useReducer instead of useState?",
+ options: [
+ "Always, it's more modern",
+ "When you have complex state logic with multiple sub-values or actions",
+ "When you want better performance",
+ "Only in class components",
+ ],
+ correctAnswer:
+ "When you have complex state logic with multiple sub-values or actions",
+ explanation:
+ "useReducer is preferable when you have complex state logic involving multiple sub-values, when the next state depends on the previous one, or when you want more predictable state updates through actions.",
+ },
+
+ {
+ id: "react-hooks-7",
+ question: "What is the main benefit of React v18's useTransition hook?",
+ options: [
+ "It speeds up all state updates",
+ "It allows marking state updates as non-urgent to keep UI responsive",
+ "It automatically batches all state updates",
+ "It replaces useEffect for better performance",
+ ],
+ correctAnswer:
+ "It allows marking state updates as non-urgent to keep UI responsive",
+ explanation:
+ "useTransition allows you to mark state updates as non-urgent (transitions), letting React prioritize more urgent updates like user input, keeping the UI responsive during heavy computations.",
+ },
+
+ {
+ id: "react-hooks-8",
+ question: "What's wrong with this custom hook code?",
+ codeSnippet: {
+ code: `function useCounter(initialValue) {
+ if (initialValue < 0) {
+ return { count: 0, increment: () => {} };
+ }
+
+ const [count, setCount] = useState(initialValue);
+ const increment = () => setCount(prev => prev + 1);
+
+ return { count, increment };
+}`,
+ language: "jsx",
+ },
+ options: [
+ "Nothing is wrong with this code",
+ "useState is called conditionally, violating the Rules of Hooks",
+ "The function name should not start with 'use'",
+ "Custom hooks cannot return objects",
+ ],
+ correctAnswer:
+ "useState is called conditionally, violating the Rules of Hooks",
+ explanation:
+ "Hooks must always be called in the same order on every render. Calling useState conditionally violates the Rules of Hooks. The hook should call useState unconditionally and handle the logic differently, such as: const [count, setCount] = useState(initialValue < 0 ? 0 : initialValue);",
+ },
+];
+
+export const reactContextQuiz = [
+ {
+ id: "context-api-1",
+ question: "What is the primary purpose of React Context API?",
+ options: [
+ "To create reusable UI components",
+ "To manage component lifecycle methods",
+ "To share data across components without prop drilling",
+ "To handle form validations",
+ ],
+ correctAnswer: "To share data across components without prop drilling",
+ explanation:
+ "React Context API is designed to solve the 'prop drilling' problem by allowing you to share state and data across your component tree without having to pass props through every level of nested components.",
+ },
+ {
+ id: "context-api-2",
+ question: "What will be logged to the console when this component renders?",
+ codeSnippet: {
+ code: `const ThemeContext = createContext('light');
+
+function DisplayTheme() {
+ const theme = useContext(ThemeContext);
+ console.log('Current theme:', theme);
+ return
Theme: {theme}
;
+}
+
+function App() {
+ return (
+
+
+
+ );
+}`,
+ language: "jsx",
+ },
+ options: [
+ "Current theme: undefined",
+ "Current theme: light",
+ "Current theme: null",
+ "Nothing is logged, an error occurs",
+ ],
+ correctAnswer: "Current theme: light",
+ explanation:
+ "When no Provider is present in the component tree, useContext returns the default value provided to createContext(). In this case, 'light' was passed as the default value.",
+ },
+ {
+ id: "context-api-3",
+ question:
+ "Which hook is recommended for consuming Context values in functional components?",
+ options: ["useEffect", "useContext", "useState", "useReducer"],
+ correctAnswer: "useContext",
+ explanation:
+ "The useContext hook is the recommended way to consume Context values in functional components. It's cleaner and more intuitive than the Context.Consumer render prop pattern.",
+ },
+ {
+ id: "context-api-4",
+ question: "What happens when this button is clicked?",
+ codeSnippet: {
+ code: `const CountContext = createContext();
+
+function CountProvider({ children }) {
+ const [count, setCount] = useState(0);
+ return (
+
+ {children}
+
+ );
+}
+
+function Counter() {
+ const { count, setCount } = useContext(CountContext);
+ return (
+
+ );
+}`,
+ language: "jsx",
+ },
+ options: [
+ "The count increases by 1 and all consumers re-render",
+ "Only the Counter component re-renders",
+ "Nothing happens because Context is immutable",
+ "An error occurs because setCount is not a function",
+ ],
+ correctAnswer: "The count increases by 1 and all consumers re-render",
+ explanation:
+ "When the Context value changes (count is updated), React automatically re-renders all components that consume that Context. The Provider creates a new value object, triggering updates to all consumers.",
+ },
+ {
+ id: "context-api-5",
+ question:
+ "What is the main performance issue with this Context implementation?",
+ codeSnippet: {
+ code: `function UserProvider({ children }) {
+ const [user, setUser] = useState(null);
+
+ return (
+ setUser(userData),
+ logout: () => setUser(null)
+ }}>
+ {children}
+
+ );
+}`,
+ language: "jsx",
+ },
+ options: [
+ "The user state is not initialized properly",
+ "New object and functions are created on every render, causing unnecessary re-renders",
+ "The Context value is undefined",
+ "There are no performance issues with this code",
+ ],
+ correctAnswer:
+ "New object and functions are created on every render, causing unnecessary re-renders",
+ explanation:
+ "The value prop creates a new object with new function references on every render. This causes all Context consumers to re-render unnecessarily, even when the actual user data hasn't changed. The solution is to use useMemo and useCallback to stabilize references.",
+ },
+ {
+ id: "context-api-6",
+ question: "When should you avoid using Context API?",
+ options: [
+ "When you need to share data between many components",
+ "When data changes very frequently and performance is critical",
+ "When implementing global application state",
+ "When you want to avoid prop drilling",
+ ],
+ correctAnswer:
+ "When data changes very frequently and performance is critical",
+ explanation:
+ "Context API causes all consumers to re-render when the value changes. For frequently changing data, this can create performance issues. In such cases, consider alternatives like state management libraries (Redux, Zustand) or keeping state local to components.",
+ },
+ {
+ id: "context-api-7",
+ question:
+ "What is the benefit of creating custom hooks for Context consumption?",
+ options: [
+ "Custom hooks make components render faster",
+ "They provide better error handling and cleaner API for consumers",
+ "They automatically optimize Context performance",
+ "They are required by React to use Context",
+ ],
+ correctAnswer:
+ "They provide better error handling and cleaner API for consumers",
+ explanation:
+ "Custom hooks like 'useTheme' or 'useAuth' encapsulate the useContext call and can provide better error messages when used outside of a Provider. They also create a cleaner, more semantic API for consuming Context values and can include additional logic or derived values.",
+ },
+];
+
+export const reactHOCQuiz = [
+ {
+ id: "hoc-basic-1",
+ question: "What will be rendered when this HOC is used?",
+ codeSnippet: {
+ code: `const withGreeting = (WrappedComponent) => {
+ return (props) => {
+ return ;
+ };
+};
+
+const DisplayMessage = ({ message, greeting }) => {
+ return
",
+ explanation:
+ "The HOC checks the isVisible prop. When isVisible is false, it returns the fallback div instead of rendering the wrapped component. The Content component never receives the props in this case.",
+ },
+ {
+ id: "hoc-composition-4",
+ question: "What will be the final props received by BaseComponent?",
+ codeSnippet: {
+ code: `const withA = (Component) => (props) =>
+ ;
+
+const withB = (Component) => (props) =>
+ ;
+
+const BaseComponent = (props) => {
+ console.log(props);
+ return
Base
;
+};
+
+const Enhanced = withA(withB(BaseComponent));
+
+function App() {
+ return ;
+}`,
+ language: "jsx",
+ },
+ options: [
+ "{ original: 'test', a: 'valueA' }",
+ "{ original: 'test', b: 'valueB' }",
+ "{ original: 'test', a: 'valueA', b: 'valueB' }",
+ "{ a: 'valueA', b: 'valueB' }",
+ ],
+ correctAnswer: "{ original: 'test', a: 'valueA', b: 'valueB' }",
+ explanation:
+ "HOCs are composed from right to left. withB wraps BaseComponent first, adding prop 'b'. Then withA wraps the result, adding prop 'a'. All props are spread through, so BaseComponent receives the original prop plus both added props.",
+ },
+ {
+ id: "hoc-state-5",
+ question:
+ "How many times will 'Counter rendered' be logged when the button is clicked twice?",
+ codeSnippet: {
+ code: `const withCounter = (WrappedComponent) => {
+ return (props) => {
+ const [count, setCount] = useState(0);
+
+ return (
+ setCount(c => c + 1)}
+ />
+ );
+ };
+};
+
+const Counter = ({ count, increment }) => {
+ console.log('Counter rendered');
+ return (
+