React is a JavaScript library for building user interfaces using declarative componentsReact uses a component-based architecture and manages UI updates through a virtual DOM to reduce direct DOM manipulation. It is used to build modular interfaces for web applications. It provides features like Hooks, context, and concurrent rendering to handle complex UI workflows.
Key Features of React
Component-Based Architecture
React applications consist of multiple components, each defined as a JavaScript function or class. A component maintains its own state using useState or class-based this.state. React triggers re-renders when the state or props change, updating only the affected parts of the virtual DOM.
Example:
function Welcome(props) {return <h1>Hello, {props.name}</h1>;}
Explanation:
- {props.name} is a JSX expression that injects the value of name from props into the DOM.
- If name = "Alice", this renders: <h1>Hello, Alice</h1>.
Virtual DOM and Efficient Rendering
React creates a virtual DOM as an in-memory representation of the real DOM. When the state or props change, React builds a new virtual DOM tree and compares it with the previous one using a diffing algorithm. It calculates the minimal set of changes and updates only the affected nodes in the real DOM.
const root = ReactDOM.createRoot(document.getElementById('root'));root.render(<App />);Explanation:
- document.getElementById('root') selects the DOM element with id="root", typically defined in index.html.
- ReactDOM.createRoot(...) initializes a React root for that container using the new concurrent rendering engine introduced in React 18.
Declarative UI
In React, the UI output depends on the application state. Components act as pure functions that return UI elements based on the current state and props. When the state changes, React re-renders the component and updates the DOM using the virtual DOM diff.
Example:
const [count, setCount] = useState(0);
return (<button onClick={() => setCount(count + 1)}>Clicked {count} times</button>);Explanation:
- Returns a JSX <button> element with an inline onClick event handler.
- onClick={() => setCount(count + 1)} increments count by 1 on each click.
- Re-renders automatically whenever setCount updates the state.
JSX Syntax
React uses JSX, a syntax extension that allows writing HTML-like tags within JavaScript code. JSX compiles to React.createElement calls, producing the virtual DOM structure. This integration simplifies component structure and aligns markup with logic in a single file.
const element = <h1>Welcome to React</h1>;Explanation:
- <h1>Welcome to React</h1> is a JSX element that compiles to React.createElement('h1', null, 'Welcome to React').
- element is now a virtual DOM object that can be rendered into the actual DOM using ReactDOM.render() or root.render() in React 18.
Unidirectional Data Flow
Data in React flows from parent to child components through props. Props are read-only values passed during component rendering. This one-way binding ensures predictable state propagation and controlled UI updates.
function Greeting({ name }) {return <h1>Hello, {name}</h1>;}Explanation:
- Uses object destructuring in the parameter list to extract name directly from props.
- Equivalent to function Greeting(props) { const name = props.name; }, but more concise.
Hooks API
React introduces Hooks to manage state and lifecycle logic in functional components. useState handles local state, while useEffect manages side effects like data fetching or subscriptions. Hooks remove the need for class-based components in most use cases.
import { useState } from 'react';
function Counter() {const [value, setValue] = useState(0);return <button onClick={() => setValue(value + 1)}>{value}</button>;}Explanation:
- Imports the useState hook from the React package.
- useState enables functional components to hold and manage internal state.
Hooks like useState, useEffect, and useContext have become standard tools for managing logic in modern React apps.
Video Processing in React
React provides a structured way to handle video content in web applications. The HTML5 <video> element serves as the foundation, while React's component-based architecture enables dynamic video controls, state management, and event handling.
Video Element Integration
React integrates the HTML5 <video> element into JSX, exposing native attributes (controls, autoPlay, loop) as declarative props. The component compiles to React.createElement('video'), bridging virtual DOM updates with browser media APIs. State-driven props and refs enable programmatic playback control without direct DOM manipulation.
Example:
function VideoPlayer() {return (<video controls width="600"><source src="example.mp4" type="video/mp4" />Your browser does not support HTML5 video.</video>);}Explanation:
- controls enables default playback UI (play/pause, volume, etc.).
- <source> specifies multiple formats for cross-browser compatibility.
State-Driven Video Controls
React's useState and useRef hooks directly control video playback state and DOM interaction. useState manages playback status (play/pause) and tracks current time, while useRef accesses the native video element for imperative operations. This maintains synchronization between React's virtual DOM and the browser's media API.
Example:
import { useRef, useState } from 'react';
function CustomVideoPlayer() {const videoRef = useRef(null);const [isPlaying, setIsPlaying] = useState(false);
const togglePlay = () => {if (isPlaying) {videoRef.current.pause();} else {videoRef.current.play();}setIsPlaying(!isPlaying);};
return (<div><video ref={videoRef} width="600" onClick={togglePlay}><source src="example.mp4" type="video/mp4" /></video><button onClick={togglePlay}>{isPlaying ? 'Pause' : 'Play'}</button></div>);}Explanation:
- useRef accesses the <video> DOM node to call native methods like play()/pause().
- isPlaying state synchronizes the button label with playback status.
Event Handling for Video Playback
React components bind to HTML5 video events (onTimeUpdate, onEnded) through synthetic event handlers. These event listeners execute callback functions that modify component state or trigger side effects, synchronizing the UI with playback progress and lifecycle events. The virtual DOM reconciliation ensures efficient updates when these events fire during media playback
Example:
function VideoWithProgress() {const [progress, setProgress] = useState(0);
const handleTimeUpdate = (e) => {const { currentTime, duration } = e.target;setProgress((currentTime / duration) * 100);};
return (<videocontrolsonTimeUpdate={handleTimeUpdate}onEnded={() => alert('Video ended!')}><source src="example.mp4" type="video/mp4" /></video>);}Explanation:
- onTimeUpdate fires continuously during playback, updating progress for custom progress bars.
- onEnded executes a callback when playback completes.
Custom Video Components
React supports the creation of encapsulated video components that expose configurable props for media sources (src) and event callbacks (onPlay, onPause). These reusable components abstract native video operations behind a declarative interface, maintaining isolation between presentation logic and media playback implementation.
Example:
function ReusableVideo({ src, onPause, onPlay }) {return (<videocontrolsonPlay={onPlay}onPause={onPause}><source src={src} type="video/mp4" /></video>);}
// Usage:<ReusableVideosrc="trailer.mp4"onPlay={() => console.log('Playback started')}onPause={() => console.log('Playback paused')}/>Explanation:
- Parent components pass event handlers (onPlay, onPause) via props for extensibility.
Dynamic Source Loading
React components assign state variables to src attributes to control video source selection at runtime. Changing the key attribute forces a full component remount, reinitializes the underlying media element, and avoids residual playback state. This aligns with React"s diffing model while supporting source switching, quality adjustments, and playlist traversal.
Example:
function MultiSourcePlayer() {const [videoSrc, setVideoSrc] = useState('hd.mp4');
return (<div><video controls key={videoSrc}><source src={videoSrc} type="video/mp4" /></video><button onClick={() => setVideoSrc('4k.mp4')}>Switch to 4K</button></div>);}Explanation:
- key forces React to re-mount the <video> element when videoSrc changes, resetting playback.
Third-Party Library Integration
React uses libraries such as react-player for platform-specific media APIs within standardized component interfaces. These libraries handle API differences internally and expose uniform props and callbacks compatible with React"s component model. This aligns external video sources with React"s rendering and update system.
Example:
import ReactPlayer from 'react-player';
function YouTubePlayer() {return (<ReactPlayerurl="https://youtu.be/example"controlswidth="800px"height="450px"/>);}Explanation:
- Abstracts platform-specific quirks (e.g., YouTube iframe API) into a consistent React component.
