react
Auto-generated from facebook/react by Mutable.ai Auto Wiki
react | |
---|---|
GitHub Repository | |
Developer | |
Written in | JavaScript |
Stars | 217k |
Watchers | 6.6k |
Created | 05/24/2013 |
Last updated | 12/25/2023 |
License | MIT |
Homepage | https://react.dev |
Repository | facebook/react |
Auto Wiki | |
Revision | 0 |
Software Version | 0.0.4Basic |
Generated from | Commit c5b937 |
Generated at | 12/25/2023 |
React is a declarative, component-based JavaScript library for building user interfaces. At its core is a system for incrementally rendering and updating UI based on state changes.
The key components of React's implementation include:
-
The reconciler, implemented in
…/react-reconciler
, which contains theReactFiberReconciler
class and algorithms for recursively diffing virtual DOM trees and scheduling rendering work. ThebeginWork
andcompleteWork
phases drive the reconciliation process. -
The scheduler, implemented in
…/scheduler
, which handles prioritizing work and yields to the browser between tasks to avoid blocking. TheScheduler
module exposes the scheduling API. -
Renderers like React DOM, implemented in
…/react-dom
, which provide environment-specific code for rendering React elements to the target platform. -
Utility modules like
…/shared
which contain shared logic used across different parts of React, including in environments like React DOM and React Native.
React components drive the UI rendering through a component-based programming model. JSX syntax is used to describe components in a declarative way. …/react
implements the component API with key classes like ReactBaseClasses
and ReactElement
.
The component lifecycle includes mounting, updating, and unmounting. ReactFiberReconciler
drives reconciliation by recursively diffing mounted component trees with new element trees to determine necessary updates. The scheduling algorithm splits work into chunks to interleave rendering with browser events.
React is designed to be flexible and pluggable, allowing environment-specific rendering while reusing core utilities. Abstractions like the HostConfig
interface enable this layer of indirection.
The build and release process relies heavily on the scripts in scripts
. Rollup bundles output formats for different targets, tasks automate workflows, and tests ensure stability across versions. The process balances automation with human oversight.
React provides a complete component model and robust implementation focused on declarative UIs, performance, and cross-environment rendering. The core algorithms, scheduling approach, and build tooling enable stable releases powering many production applications.
React Component Model
References: packages/react
, packages/shared
React's component-based architecture revolves around building user interfaces out of small, reusable components that accept data and callbacks as inputs and return React elements describing what should appear on the screen. This allows encapsulating and separating UI logic from state logic in a declarative way.
Component API
Components are defined in React using classes or functions. The Component
class serves as the base class for standard React components. It defines common functionality like local state, props, context, refs, and methods to update them.
Managing State
Local component state is managed through the Component
base class defined in …/ReactBaseClasses.js
. Component
serves as the foundation for all React components and defines common functionality like storing local state, context, and refs.
JSX Processing
References: packages/react/src/jsx
, packages/react/src/ReactElement.js
The core functionality of parsing JSX and constructing React elements is handled across several key files in the …/jsx
directory.
Utilities
The ReactChildren
module provides utilities for working with React children. The core functions are mapChildren
, countChildren
, forEachChildren
, and toArray
. mapChildren
takes children, a mapping function, and context, and uses mapIntoArray
to recursively map over the children, handling different child types like strings, numbers, elements, arrays, and iterables. For elements, it will clone the element and replace its key if needed before adding it to the output array.
Type Checking
References: packages/react/src/ReactElementValidator.js
The ReactElementValidator
provides type checking for React elements and props. It exports functions like jsxWithValidation
, createElementWithValidation
, and cloneElementWithValidation
that wrap the normal element creation functions and perform several validations.
Error Handling
References: packages/shared/ReactErrorUtils.js
React provides consistent error handling across environments through utilities in the …/ReactErrorUtils.js
file. This file contains functions for handling errors during guarded function calls in React.
Memoization
References: packages/react/src/ReactMemo.js
PureComponent and memo()
provide optimizations for performance by memoizing component renders. When a component wrapped in memo()
re-renders with identical props, React will skip the render and reuse the previous result. This prevents unnecessary re-renders of components.
Testing Utilities
References: packages/react/src/__tests__
, packages/react-test-renderer
The React test renderer provides utilities for testing React components in isolation without depending on the DOM or native mobile environments. The ReactTestRenderer
class defined in …/ReactTestRenderer.js
allows rendering components to plain JavaScript objects, enabling snapshot testing and inspecting component output. Key utilities include ReactTestRenderer
and the act()
function exported from …/ReactTestRendererAct-test.js
.
Rendering Implementation
References: packages/react-reconciler
, packages/scheduler
, packages/react-dom
The core reconciliation, scheduling, and rendering algorithms in React are implemented across multiple packages and modules. The key components are:
Reconciliation
References: packages/react-reconciler/src
, packages/react-reconciler/src/ReactFiberCompleteWork.js
, packages/react-reconciler/src/ReactChildFiber.js
The core reconciliation algorithm in React incrementally updates the virtual DOM tree to match the actual DOM nodes on the page. This process, known as reconciliation, handles inserting, removing, and updating DOM nodes based on changes to the component tree.
Scheduling
The React scheduler is responsible for scheduling and executing rendering work like component updates in a way that is efficient and respects priorities. At the core of the scheduler is the concept of tasks, which represent units of work like rendering callbacks. Tasks are assigned priority levels and added to priority queues, where they are processed synchronously by the scheduler's work loop.
Renderers
The …/react-reconciler
package provides the core reconciliation logic that is shared between React DOM and other renderers. It defines abstract interfaces that different renderers implement to integrate with React.
Hydration
References: packages/react-dom/src/client/ReactDOM.js
The hydrate()
function in …/ReactDOM.js
is the main entry point for hydrating server-rendered HTML strings into React DOM trees. It calls functions which handle the actual hydration logic.
Testing Utilities
The …/__tests__
directory contains utilities for testing React component rendering behavior and output without involving a real DOM. This allows focusing tests solely on React's core reconciliation and rendering algorithms.
Build and Release Process
References: scripts/release
, scripts/rollup
, scripts/tasks
The React build and release process leverages many scripts, configurations, and utilities to orchestrate building, testing, and publishing releases. The core functionality involves:
Build Scripts
References: scripts/rollup
The core build scripts and utilities for React are located in the …/rollup
directory. This directory contains all of the configuration and logic needed to build React and related packages using the Rollup bundler.
Testing and Validation
References: scripts/jest
, scripts/tasks/flow.js
, scripts/rollup/validate
The core functionality of testing React builds and validating outputs is handled through Jest and ESLint integration. Jest is used to run unit and integration tests against React packages and components, while ESLint validates final build artifacts.
Release Automation
References: scripts/release
The core functionality for automating the React release process is contained within the …/release
directory. This directory contains scripts and utilities that handle tasks like building releases locally, preparing releases from continuous integration (CI) builds, preparing releases from npm, and publishing releases to npm.
Build Configuration
References: scripts/rollup/bundles.js
The build configuration for React is defined in …/bundles.js
. This file specifies the different bundleTypes
that can be built like UMD, ESM, and NODE. It also defines moduleTypes
which categorize bundles as ISOMORPHIC, RENDERER, or RENDERER_UTILS.
Build Infrastructure
References: scripts/circleci
The React codebase leverages continuous integration services to run automated tests and validate code quality during the development process. CircleCI is used to test React and its related packages, with scripts defined in …/circleci
to facilitate this.
Change Management
References: react
The …/release
directory contains scripts and utilities for managing changes to React's build and release processes over time. As React has grown, the build system has evolved to support additional platforms and features. The scripts in this directory help evolve the build process in a modular, incremental way.
Performance Tracking
References: scripts/rollup/stats.js
The …/stats.js
file contains utilities for tracking bundle sizes across builds and comparing results to previous builds. It saves data for the current build to the currentBuildResults
object and previous build data to prevBuildResults
.
Environment Management
References: react
The …/shared
directory contains utilities for managing environment variables and configurations across the React codebase. This is important for handling different environments like development versus production and ensuring consistent behavior.
Documentation
References: react
The documentation section would cover how the build and release processes are documented within the codebase. Key aspects related to documentation include:
Testing Utilities
References: scripts/jest
, fixtures
The core functionality for testing React components and core functionality is implemented across several directories and files in the React repository. The key areas are:
Test Utilities
References: packages/react/src/__tests__
, packages/react-test-renderer
The …/__tests__
directory contains utilities that are helpful for testing React components. This includes the ReactTestRenderer
exported from …/react-test-renderer
. It allows rendering React components to plain JavaScript objects, enabling testing the component rendering output in isolation. Some key methods on the renderer instance include toJSON()
to serialize the tree to JSON, and update()
to re-render with new props.
DOM Testing
References: packages/react-dom/src/__tests__
The …/__tests__
directory contains extensive tests for the functionality in the react-dom package. It aims to thoroughly test all aspects of rendering React components to the DOM, updating components, handling events, focusing elements, and more.
Renderer Testing
References: packages/react-reconciler/src/__tests__
The core functionality covered under Renderer Testing is testing React's reconciliation and rendering algorithms by simulating the rendering process without involving a real DOM. This allows focusing the tests solely on React's core reconciliation behavior rather than interactions with the environment.
Jest Utilities
References: scripts/jest
The …/jest
directory contains custom Jest plugins and utilities that are used to test React components and core functionality. It provides tools and integrations that are important for testing React code.
Test Fixtures
References: fixtures
The Test Fixtures directory contains example applications and components used for testing React functionality. These fixtures provide standardized implementations that can be reliably tested across different environments.
DevTools Integration
This section covers integrations with React Developer Tools for debugging components. The core functionality provided by the code relates to enabling inspection and debugging of React components in the browser.
React DevTools Core
The Bridge
class defined in …/backend.js
is central to communication between the frontend DevTools UI and the backend server. It handles listening for messages from both sides and sending responses. A Bridge
instance is initialized when connecting to the backend server in …/standalone.js
via connectToSocket()
. This function also initializes the important Store
class, which holds the inspected React component tree displayed in the UI.
Browser Extensions
References: packages/react-devtools-extensions/src
, packages/react-devtools-extensions/chrome
, packages/react-devtools-extensions/firefox
, packages/react-devtools-extensions/edge
The React DevTools extensions leverage shared logic across different browser implementations through abstraction layers. The core functionality is defined in the …/react-devtools-extensions
package and its sub-packages.
Building and Deploying
References: scripts/devtools
The React DevTools extensions are built and deployed through a series of scripts that automate the process. The …/build-and-test.js
script handles building and testing the React DevTools packages, including react-devtools-core, react-devtools-inline, and react-devtools-extensions.
Testing Utilities
References: packages/react-devtools-extensions/src/__tests__
This section details the testing utilities used for React DevTools components. The core functionality is validating that the DevTools extensions package is producing source maps correctly for local development and production builds.
Communication
References: packages/react-devtools-core/src/backend.js
, packages/react-devtools-extensions/src/main/index.js
The core functionality of communicating between the DevTools frontend and backend is handled by the Bridge
class. The Bridge
is initialized when the DevTools extension loads by the createBridgeAndStore()
function in …/index.js
.
User Interface
References: packages/react-devtools-core/src/standalone.js
The DevTools UI is rendered and updated via the …/standalone.js
file. This file contains the core logic for running the React DevTools standalone app.
Component Inspection
References: packages/react-devtools-core/src/backend.js
The Agent
class initialized in …/backend.js
serves as the main interface between the React DevTools backend and frontend. The Agent
handles inspecting and displaying component data by providing methods for retrieving component information from the backend.
Configuration
References: react
The …/devtools
directory contains scripts and utilities related to building, testing, and publishing releases of the React Developer Tools browser extensions.
Browser Integration
The core functionality of integrating the React DevTools extension with browsers is handled through the background scripts. The …/background
directory contains the main logic for the extension.
Error Handling
References: scripts/error-codes
The React codebase includes utilities for handling errors consistently across environments. The …/ReactErrorUtils.js
module provides functions for logging errors to the console in a standardized way.
Error Codes
References: scripts/error-codes
The React codebase standardizes error messages for consistent debugging. The …/error-codes
directory contains utilities that map error messages to unique codes. This improves debugging by replacing verbose error messages with standardized IDs in production builds.
Boundaries
References: react
Error handling is implemented through the ErrorBoundary
component. The ErrorBoundary
component catches errors in its child components using the standard React error handling lifecycle methods.
Logging
References: packages/shared/ReactErrorUtils.js
The ReactErrorUtils.js file contains utilities for consistently logging errors across environments in React. The invokeGuardedCallback()
function is used to call other functions and guard against errors. If an error occurs, it is captured by the reporter
object's onError()
method.
Warnings
References: react
The …/print-warnings
directory contains a script that extracts all warning messages from React code for output and change tracking purposes. This helps manage warnings across releases by providing a complete list of all unique warnings emitted from the codebase.
Flow Integration
References: scripts/flow
Flow Integration leverages Flow's type system to improve type safety across React and its various platforms through module declarations and type augmentation. The key files that enable this are:
Type Checking
References: scripts/flow
The …/flow
directory leverages Flow's type system to enable static type checking throughout the React codebase. Flow type declarations are provided for core React components, APIs, and the runtime environment. This improves type safety and allows errors to be caught during development.
Configuration
References: scripts/flow/createFlowConfigs.js
The …/createFlowConfigs.js
file is responsible for programmatically generating Flow configuration files tailored for each React renderer. It scans package directories to find "forked" variant files for different renderers, storing them in the allForks
set. The findForks()
function searches for a file's "forks" subdirectory to discover variant files, storing their base paths in the forkedFiles
map.
Environment
References: scripts/flow/environment.js
The file …/environment.js
plays an important role in improving type safety within the React codebase by declaring types and modules to model the runtime environment for Flow's static type checker. This allows Flow to understand how React components interact with things like React elements, feature flags, error handling modules, and common dependencies.
React Native
References: scripts/flow/react-native-host-hooks.js
The file …/react-native-host-hooks.js
bridges private React Native APIs that are not normally visible to Flow. It defines Flow types for callbacks and functions used internally by React Native, like __MeasureOnSuccessCallback
for measuring views.
Utilities
References: scripts/flow/runFlow.js
The runFlow
function in …/runFlow.js
is used to run Flow type checking on a specific React renderer. It handles configuration setup, spawning Flow as a child process, and checking the return code.