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
{greeting} {message}
; +}; + +const EnhancedComponent = withGreeting(DisplayMessage); + +function App() { + return ; +}`, + language: "jsx", + }, + options: [ + "
Hello World
", + "
World
", + "
Hello
", + "Nothing renders, an error occurs", + ], + correctAnswer: "
Hello World
", + explanation: + "The HOC withGreeting adds a 'greeting' prop with value 'Hello' to the wrapped component. The DisplayMessage component receives both the original 'message' prop ('World') and the injected 'greeting' prop ('Hello'), rendering 'Hello World'.", + }, + { + id: "hoc-props-2", + question: "What props will MyComponent receive?", + codeSnippet: { + code: `const withData = (WrappedComponent) => { + return (props) => { + const data = { id: 1, name: 'John' }; + return ; + }; +}; + +const MyComponent = (props) => { + console.log(Object.keys(props)); + return
Component
; +}; + +const Enhanced = withData(MyComponent); + +function App() { + return ; +}`, + language: "jsx", + }, + options: [ + "['title', 'value']", + "['data', 'enhanced']", + "['title', 'value', 'data', 'enhanced']", + "['data']", + ], + correctAnswer: "['title', 'value', 'data', 'enhanced']", + explanation: + "The HOC spreads all original props (...props) and adds new props (data and enhanced). MyComponent receives all props: the original ones ('title', 'value') and the ones added by the HOC ('data', 'enhanced').", + }, + { + id: "hoc-conditional-3", + question: "What will be rendered when isVisible is false?", + codeSnippet: { + code: `const withConditionalRender = (WrappedComponent) => { + return ({ isVisible, ...props }) => { + if (!isVisible) { + return
Component is hidden
; + } + return ; + }; +}; + +const Content = ({ text }) =>

{text}

; + +const ConditionalContent = withConditionalRender(Content); + +function App() { + return ; +}`, + language: "jsx", + }, + options: [ + "

Hello

", + "
Component is hidden
", + "Nothing renders", + "An error occurs", + ], + correctAnswer: "
Component is hidden
", + 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

Hello, {this.props.name}!

; + } +} +``` + +### Class Component with State + +```jsx +class Counter extends Component { + constructor(props) { + super(props); + this.state = { count: 0 }; + } + + increment = () => { + this.setState({ count: this.state.count + 1 }); + }; + + render() { + return ( +
+

Count: {this.state.count}

+ +
+ ); + } +} +``` + +### Lifecycle Methods + +```jsx +class DataComponent extends Component { + componentDidMount() { + // Fetch data after component mounts + this.fetchData(); + } + + componentDidUpdate(prevProps) { + // Re-fetch if props changed + if (prevProps.userId !== this.props.userId) { + this.fetchData(); + } + } + + componentWillUnmount() { + // Clean up subscriptions, cancel requests + this.cleanup(); + } + + render() { + return
{this.state.data}
; + } +} +``` + +### 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 ( +
+ setFilter(e.target.value)} /> + {filteredItems.map((item) => ( +
{item.name}
+ ))} +
+ ); +} +``` + +--- + +### 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 ( +
+

Count: {state.count}

+ + + + +
+ ); +} +``` + +--- + +## Few of React v18, v19 Hooks + +### 1. useTransition + +**Purpose:** Mark state updates as non-urgent to keep UI responsive + +**Syntax:** + +```javascript +const [isPending, startTransition] = useTransition(); +``` + +**Example:** + +```javascript +import { useTransition, useState } from "react"; + +function SearchApp() { + const [isPending, startTransition] = useTransition(); + const [input, setInput] = useState(""); + const [list, setList] = useState([]); + + const handleChange = (e) => { + setInput(e.target.value); // Urgent update + + startTransition(() => { + // Non-urgent update - won't block input typing + const filtered = heavyFilterOperation(e.target.value); + setList(filtered); + }); + }; + + return ( +
+ + {isPending &&
Updating results...
} + +
+ ); +} +``` + +--- + +### 2. useDeferredValue + +**Purpose:** Defer updating non-critical UI parts until more urgent updates complete + +**Syntax:** + +```javascript +const deferredValue = useDeferredValue(value); +``` + +**Example:** + +```javascript +import { useDeferredValue, useState, useMemo } from "react"; + +function SearchResults({ query }) { + const deferredQuery = useDeferredValue(query); + + const results = useMemo(() => { + // This expensive calculation uses deferred value + // Won't block typing in the search input + return searchItems(deferredQuery); + }, [deferredQuery]); + + return ( +
+
Searching for: {deferredQuery}
+ {results.map((item) => ( +
{item.name}
+ ))} +
+ ); +} + +function App() { + const [query, setQuery] = useState(""); + + return ( +
+ setQuery(e.target.value)} + placeholder="Search..." + /> + +
+ ); +} +``` + +--- + +### 3. useId + +**Purpose:** Generate unique IDs for accessibility attributes + +**Syntax:** + +```javascript +const id = useId(); +``` + +**Example:** + +```javascript +import { useId } from "react"; + +function FormField({ label, type = "text" }) { + const id = useId(); + + return ( +
+ + +
Help text for {label}
+
+ ); +} + +function LoginForm() { + return ( +
+ + + + ); +} +``` + +--- + +### 4. use (Experimental) + +**Purpose:** Read promises and context values directly in components + +**Syntax:** + +```javascript +const value = use(promise); +const value = use(context); +``` + +**Example:** + +```javascript +import { use, Suspense } from "react"; + +// Promise-based data fetching +function UserProfile({ userId }) { + const user = use(fetchUser(userId)); // Reads promise directly + + return ( +
+

{user.name}

+

{user.email}

+
+ ); +} + +// Context reading +const ThemeContext = React.createContext(); + +function ThemedButton() { + const theme = use(ThemeContext); // Alternative to useContext + + return ( + + ); +} + +function App() { + return ( + + Loading...}> + + + + + ); +} +``` + +--- + +### 5. useFormStatus + +**Purpose:** Get status of form submissions + +**Syntax:** + +```javascript +const { pending, data, method, action } = useFormStatus(); +``` + +**Example:** + +```javascript +import { useFormStatus } from "react-dom"; + +function SubmitButton() { + const { pending } = useFormStatus(); + + return ( + + ); +} + +function ContactForm() { + async function submitForm(formData) { + // Simulate API call + await new Promise((resolve) => setTimeout(resolve, 2000)); + console.log("Form submitted:", Object.fromEntries(formData)); + } + + return ( +
+ + +