- Spec files
npm-react
Describes: pkg:npm/react@18.3.x
- Description
- React is a JavaScript library for building user interfaces with declarative, component-based architecture.
- Author
- tessl
- Last updated
index.md docs/
1# React23React is a JavaScript library for building user interfaces that emphasizes declarative programming, component-based architecture, and efficient rendering. It enables developers to create interactive UIs through composable components that manage their own state and efficiently update when data changes.45## Package Information67- **Package Name**: react8- **Package Type**: npm9- **Language**: JavaScript/TypeScript10- **Installation**: `npm install react`1112## Core Imports1314```javascript15import React from 'react';16// Access: React.useState, React.Component, etc.17```1819Named imports:2021```javascript22import { useState, useEffect, Component, Fragment } from 'react';23```2425For CommonJS:2627```javascript28const React = require('react');29const { useState, useEffect, Component } = require('react');30```3132JSX Runtime (automatic - handled by transpilers):3334```javascript35import { jsx, jsxs, Fragment } from 'react/jsx-runtime';36```3738## Basic Usage3940```javascript41import React, { useState, useEffect } from 'react';4243// Function component with hooks44function Counter() {45const [count, setCount] = useState(0);4647useEffect(() => {48document.title = `Count: ${count}`;49}, [count]);5051return (52<div>53<p>You clicked {count} times</p>54<button onClick={() => setCount(count + 1)}>55Click me56</button>57</div>58);59}6061// Class component62class Timer extends React.Component {63constructor(props) {64super(props);65this.state = { seconds: 0 };66}6768componentDidMount() {69this.interval = setInterval(() => {70this.setState({ seconds: this.state.seconds + 1 });71}, 1000);72}7374componentWillUnmount() {75clearInterval(this.interval);76}7778render() {79return <div>Seconds: {this.state.seconds}</div>;80}81}82```8384## Architecture8586React is built around several key concepts:8788- **Components**: Reusable UI building blocks that can be function or class-based89- **Virtual DOM**: Efficient reconciliation system that minimizes direct DOM manipulation90- **Unidirectional Data Flow**: Props flow down, events flow up for predictable state management91- **Hooks**: Functions that let you use state and lifecycle features in function components92- **Context**: Built-in state management system for sharing data across component trees93- **Concurrent Features**: Modern React includes features for handling async operations and non-urgent updates9495## Capabilities9697### React Hooks9899Complete set of built-in hooks for state management, side effects, performance optimization, and more. Essential for modern React development with function components.100101```javascript { .api }102// State hooks103function useState<S>(initialState: S | (() => S)): [S, (value: S | ((prev: S) => S)) => void];104function useReducer<R extends Reducer<any, any>>(reducer: R, initialState: ReducerState<R>): [ReducerState<R>, Dispatch<ReducerAction<R>>];105106// Effect hooks107function useEffect(effect: EffectCallback, deps?: DependencyList): void;108function useLayoutEffect(effect: EffectCallback, deps?: DependencyList): void;109function useInsertionEffect(effect: EffectCallback, deps?: DependencyList): void;110111// Performance hooks112function useMemo<T>(factory: () => T, deps: DependencyList): T;113function useCallback<T extends Function>(callback: T, deps: DependencyList): T;114```115116[React Hooks](./hooks.md)117118### Component Classes119120Base classes for creating class-based React components with lifecycle methods and state management.121122```javascript { .api }123class Component<P = {}, S = {}, SS = any> {124constructor(props: P);125setState<K extends keyof S>(state: ((prevState: S, props: P) => Pick<S, K> | S | null) | Pick<S, K> | S | null, callback?: () => void): void;126forceUpdate(callback?: () => void): void;127render(): ReactNode;128}129130class PureComponent<P = {}, S = {}, SS = any> extends Component<P, S, SS> {}131```132133[Component Classes](./components.md)134135### Element Creation & Manipulation136137Core functions for creating and manipulating React elements, essential for JSX alternatives and dynamic element creation.138139```javascript { .api }140function createElement<P extends {}>(type: ReactType, props?: Attributes & P | null, ...children: ReactNode[]): ReactElement<P>;141function cloneElement<P extends {}>(element: ReactElement<P>, props?: Partial<P> & Attributes | null, ...children: ReactNode[]): ReactElement<P>;142function isValidElement<P>(object: {} | null | undefined): object is ReactElement<P>;143```144145[Element Creation](./elements.md)146147### Built-in Components148149Special React components for layout, performance profiling, and development features.150151```javascript { .api }152const Fragment: ExoticComponent<{ children?: ReactNode }>;153const StrictMode: ExoticComponent<{ children?: ReactNode }>;154const Profiler: ExoticComponent<ProfilerProps>;155const Suspense: ExoticComponent<SuspenseProps>;156const SuspenseList: ExoticComponent<SuspenseListProps>;157```158159[Built-in Components](./builtin-components.md)160161### Context API162163Create and consume context for sharing data across component trees without prop drilling.164165```javascript { .api }166function createContext<T>(defaultValue: T): Context<T>;167function createServerContext<T>(globalName: string, defaultValue: T): ServerContext<T>;168169interface Context<T> {170Provider: ExoticComponent<ProviderProps<T>>;171Consumer: ExoticComponent<ConsumerProps<T>>;172displayName?: string;173}174```175176[Context API](./context.md)177178### Higher-Order Components179180Utilities for enhancing components with additional functionality like memoization, ref forwarding, and lazy loading.181182```javascript { .api }183function memo<P extends object>(Component: FunctionComponent<P>, propsAreEqual?: (prevProps: P, nextProps: P) => boolean): NamedExoticComponent<P>;184function forwardRef<T, P = {}>(render: ForwardRefRenderFunction<T, P>): ForwardRefExoticComponent<PropsWithoutRef<P> & RefAttributes<T>>;185function lazy<T extends ComponentType<any>>(factory: () => Promise<{ default: T }>): LazyExoticComponent<T>;186```187188[Higher-Order Components](./hoc.md)189190### Children Utilities191192Utilities for working with props.children, including mapping, filtering, and validating child elements.193194```javascript { .api }195const Children: {196map<T, C>(children: C | ReadonlyArray<C>, fn: (child: C, index: number) => T): C extends null | undefined ? C : Array<Exclude<T, boolean | null | undefined>>;197forEach<C>(children: C | ReadonlyArray<C>, fn: (child: C, index: number) => void): void;198count(children: any): number;199only<C>(children: C): C extends any[] ? never : C;200toArray(children: ReactNode | ReactNode[]): Array<Exclude<ReactNode, boolean | null | undefined>>;201};202```203204[Children Utilities](./children.md)205206### Concurrent Features207208Modern React features for handling async operations and optimizing performance with transitions and deferred values.209210```javascript { .api }211function startTransition(scope: () => void): void;212function useTransition(): [boolean, (callback: () => void) => void];213function useDeferredValue<T>(value: T): T;214```215216[Concurrent Features](./concurrent.md)217218### References & Utilities219220Reference management and utility functions for accessing DOM elements and creating stable references.221222```javascript { .api }223function createRef<T = any>(): RefObject<T>;224function useRef<T = undefined>(): MutableRefObject<T | undefined>;225function useImperativeHandle<T, R extends T>(ref: Ref<T> | undefined, init: () => R, deps?: DependencyList): void;226const version: string;227```228229[References & Utilities](./refs.md)230231### JSX Runtime232233Low-level JSX transformation functions used by transpilers to convert JSX syntax into JavaScript function calls.234235```javascript { .api }236// Production runtime237function jsx(type: any, props: any, key?: any): ReactElement;238function jsxs(type: any, props: any, key?: any): ReactElement;239240// Development runtime241function jsxDEV(type: any, props: any, key?: any, isStaticChildren?: boolean, source?: any, self?: any): ReactElement;242```243244[JSX Runtime](./jsx-runtime.md)245246### Experimental APIs247248Experimental and unstable APIs that may change in future versions. Use with caution in production applications.249250```javascript { .api }251// Experimental components252const unstable_Cache: ExoticComponent<{ children?: ReactNode }>;253const unstable_DebugTracingMode: ExoticComponent<{ children?: ReactNode }>;254const unstable_LegacyHidden: ExoticComponent<{ children?: ReactNode; mode: 'hidden' | 'unstable-defer-without-hiding' }>;255const unstable_Offscreen: ExoticComponent<{ children?: ReactNode; mode?: 'hidden' | 'visible' }>;256const unstable_Scope: ExoticComponent<{ children?: ReactNode }>;257const unstable_TracingMarker: ExoticComponent<{ children?: ReactNode; name: string }>;258259// Experimental cache functions260function unstable_getCacheSignal(): AbortSignal;261function unstable_getCacheForType<T>(resourceType: () => T): T;262function unstable_useCacheRefresh(): () => void;263```264265These experimental APIs are subject to change and should only be used for testing React's upcoming features.266267## Types268269```javascript { .api }270// Core types271type ReactNode = ReactChild | ReactFragment | ReactPortal | boolean | null | undefined;272type ReactChild = ReactElement | ReactText;273type ReactText = string | number;274type ReactFragment = {} | Iterable<ReactNode>;275276// Component types277type FunctionComponent<P = {}> = (props: PropsWithChildren<P>, context?: any) => ReactElement<any, any> | null;278type ComponentType<P = {}> = ComponentClass<P> | FunctionComponent<P>;279280// Element types281interface ReactElement<P = any, T extends string | JSXElementConstructor<any> = string | JSXElementConstructor<any>> {282type: T;283props: P;284key: Key | null;285}286287// Ref types288type Ref<T> = RefCallback<T> | RefObject<T> | null;289interface RefObject<T> {290readonly current: T | null;291}292interface MutableRefObject<T> {293current: T;294}295```