- | React.ReactPortal
- | boolean
- | null
- | undefined
- | React.DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_REACT_NODES[
- keyof React.DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_REACT_NODES
- ];
-
-/**
- * The function returned from an effect passed to {@link React.useEffect useEffect},
- * which can be used to clean up the effect when the component unmounts.
- *
- * @see {@link https://react.dev/reference/react/useEffect React Docs}
- */
-type Destructor = () => void | { [UNDEFINED_VOID_ONLY]: never };
-type VoidOrUndefinedOnly = void | { [UNDEFINED_VOID_ONLY]: never };
-
-// eslint-disable-next-line @definitelytyped/export-just-namespace
-export = React;
-export as namespace React;
-
-declare namespace React {
- //
- // React Elements
- // ----------------------------------------------------------------------
-
- /**
- * Used to retrieve the possible components which accept a given set of props.
- *
- * Can be passed no type parameters to get a union of all possible components
- * and tags.
- *
- * Is a superset of {@link ComponentType}.
- *
- * @template P The props to match against. If not passed, defaults to any.
- * @template Tag An optional tag to match against. If not passed, attempts to match against all possible tags.
- *
- * @example
- *
- * ```tsx
- * // All components and tags (img, embed etc.)
- * // which accept `src`
- * type SrcComponents = ElementType<{ src: any }>;
- * ```
- *
- * @example
- *
- * ```tsx
- * // All components
- * type AllComponents = ElementType;
- * ```
- *
- * @example
- *
- * ```tsx
- * // All custom components which match `src`, and tags which
- * // match `src`, narrowed down to just `audio` and `embed`
- * type SrcComponents = ElementType<{ src: any }, 'audio' | 'embed'>;
- * ```
- */
- type ElementType =
- | { [K in Tag]: P extends JSX.IntrinsicElements[K] ? K : never }[Tag]
- | ComponentType
;
-
- /**
- * Represents any user-defined component, either as a function or a class.
- *
- * Similar to {@link JSXElementConstructor}, but with extra properties like
- * {@link FunctionComponent.defaultProps defaultProps }.
- *
- * @template P The props the component accepts.
- *
- * @see {@link ComponentClass}
- * @see {@link FunctionComponent}
- */
- type ComponentType
= ComponentClass
| FunctionComponent
;
-
- /**
- * Represents any user-defined component, either as a function or a class.
- *
- * Similar to {@link ComponentType}, but without extra properties like
- * {@link FunctionComponent.defaultProps defaultProps }.
- *
- * @template P The props the component accepts.
- */
- type JSXElementConstructor
=
- | ((
- props: P,
- ) => ReactNode | Promise)
- // constructor signature must match React.Component
- | (new(props: P, context: any) => Component);
-
- /**
- * Created by {@link createRef}, or {@link useRef} when passed `null`.
- *
- * @template T The type of the ref's value.
- *
- * @example
- *
- * ```tsx
- * const ref = createRef();
- *
- * ref.current = document.createElement('div'); // Error
- * ```
- */
- interface RefObject {
- /**
- * The current value of the ref.
- */
- current: T;
- }
-
- interface DO_NOT_USE_OR_YOU_WILL_BE_FIRED_CALLBACK_REF_RETURN_VALUES {
- }
- /**
- * A callback fired whenever the ref's value changes.
- *
- * @template T The type of the ref's value.
- *
- * @see {@link https://react.dev/reference/react-dom/components/common#ref-callback React Docs}
- *
- * @example
- *
- * ```tsx
- * console.log(node)} />
- * ```
- */
- type RefCallback
= {
- bivarianceHack(
- instance: T | null,
- ):
- | void
- | (() => VoidOrUndefinedOnly)
- | DO_NOT_USE_OR_YOU_WILL_BE_FIRED_CALLBACK_REF_RETURN_VALUES[
- keyof DO_NOT_USE_OR_YOU_WILL_BE_FIRED_CALLBACK_REF_RETURN_VALUES
- ];
- }["bivarianceHack"];
-
- /**
- * A union type of all possible shapes for React refs.
- *
- * @see {@link RefCallback}
- * @see {@link RefObject}
- */
-
- type Ref = RefCallback | RefObject | null;
- /**
- * @deprecated Use `Ref` instead. String refs are no longer supported.
- * If you're typing a library with support for React versions with string refs, use `RefAttributes['ref']` instead.
- */
- type LegacyRef = Ref;
- /**
- * @deprecated Use `ComponentRef` instead
- *
- * Retrieves the type of the 'ref' prop for a given component type or tag name.
- *
- * @template C The component type.
- *
- * @example
- *
- * ```tsx
- * type MyComponentRef = React.ElementRef;
- * ```
- *
- * @example
- *
- * ```tsx
- * type DivRef = React.ElementRef<'div'>;
- * ```
- */
- type ElementRef<
- C extends
- | ForwardRefExoticComponent
- | { new(props: any, context: any): Component }
- | ((props: any) => ReactNode)
- | keyof JSX.IntrinsicElements,
- > = ComponentRef;
-
- type ComponentState = any;
-
- /**
- * A value which uniquely identifies a node among items in an array.
- *
- * @see {@link https://react.dev/learn/rendering-lists#keeping-list-items-in-order-with-key React Docs}
- */
- type Key = string | number | bigint;
-
- /**
- * @internal The props any component can receive.
- * You don't have to add this type. All components automatically accept these props.
- * ```tsx
- * const Component = () => ;
- *
- * ```
- *
- * WARNING: The implementation of a component will never have access to these attributes.
- * The following example would be incorrect usage because {@link Component} would never have access to `key`:
- * ```tsx
- * const Component = (props: React.Attributes) => props.key;
- * ```
- */
- interface Attributes {
- key?: Key | null | undefined;
- }
- /**
- * The props any component accepting refs can receive.
- * Class components, built-in browser components (e.g. `div`) and forwardRef components can receive refs and automatically accept these props.
- * ```tsx
- * const Component = forwardRef(() => );
- * console.log(current)} />
- * ```
- *
- * You only need this type if you manually author the types of props that need to be compatible with legacy refs.
- * ```tsx
- * interface Props extends React.RefAttributes {}
- * declare const Component: React.FunctionComponent;
- * ```
- *
- * Otherwise it's simpler to directly use {@link Ref} since you can safely use the
- * props type to describe to props that a consumer can pass to the component
- * as well as describing the props the implementation of a component "sees".
- * {@link RefAttributes} is generally not safe to describe both consumer and seen props.
- *
- * ```tsx
- * interface Props extends {
- * ref?: React.Ref | undefined;
- * }
- * declare const Component: React.FunctionComponent;
- * ```
- *
- * WARNING: The implementation of a component will not have access to the same type in versions of React supporting string refs.
- * The following example would be incorrect usage because {@link Component} would never have access to a `ref` with type `string`
- * ```tsx
- * const Component = (props: React.RefAttributes) => props.ref;
- * ```
- */
- interface RefAttributes extends Attributes {
- /**
- * Allows getting a ref to the component instance.
- * Once the component unmounts, React will set `ref.current` to `null`
- * (or call the ref with `null` if you passed a callback ref).
- *
- * @see {@link https://react.dev/learn/referencing-values-with-refs#refs-and-the-dom React Docs}
- */
- ref?: Ref | undefined;
- }
-
- /**
- * Represents the built-in attributes available to class components.
- */
- interface ClassAttributes extends RefAttributes {
- }
-
- /**
- * Represents a JSX element.
- *
- * Where {@link ReactNode} represents everything that can be rendered, `ReactElement`
- * only represents JSX.
- *
- * @template P The type of the props object
- * @template T The type of the component or tag
- *
- * @example
- *
- * ```tsx
- * const element: ReactElement = ;
- * ```
- */
- interface ReactElement<
- P = unknown,
- T extends string | JSXElementConstructor = string | JSXElementConstructor,
- > {
- type: T;
- props: P;
- key: string | null;
- }
-
- /**
- * @deprecated
- */
- interface ReactComponentElement<
- T extends keyof JSX.IntrinsicElements | JSXElementConstructor,
- P = Pick, Exclude, "key" | "ref">>,
- > extends ReactElement> {}
-
- /**
- * @deprecated Use `ReactElement
>`
- */
- interface FunctionComponentElement
extends ReactElement
> {
- /**
- * @deprecated Use `element.props.ref` instead.
- */
- ref?: ("ref" extends keyof P ? P extends { ref?: infer R | undefined } ? R : never : never) | undefined;
- }
-
- /**
- * @deprecated Use `ReactElement
>`
- */
- type CElement
> = ComponentElement
;
- /**
- * @deprecated Use `ReactElement
>`
- */
- interface ComponentElement
> extends ReactElement
> {
- /**
- * @deprecated Use `element.props.ref` instead.
- */
- ref?: Ref | undefined;
- }
-
- /**
- * @deprecated Use {@link ComponentElement} instead.
- */
- type ClassicElement = CElement
>;
-
- // string fallback for custom web-components
- /**
- * @deprecated Use `ReactElement
`
- */
- interface DOMElement
| SVGAttributes, T extends Element>
- extends ReactElement
- {
- /**
- * @deprecated Use `element.props.ref` instead.
- */
- ref: Ref;
- }
-
- // ReactHTML for ReactHTMLElement
- interface ReactHTMLElement extends DetailedReactHTMLElement, T> {}
-
- interface DetailedReactHTMLElement, T extends HTMLElement> extends DOMElement
{
- type: HTMLElementType;
- }
-
- // ReactSVG for ReactSVGElement
- interface ReactSVGElement extends DOMElement, SVGElement> {
- type: SVGElementType;
- }
-
- interface ReactPortal extends ReactElement {
- children: ReactNode;
- }
-
- /**
- * Different release channels declare additional types of ReactNode this particular release channel accepts.
- * App or library types should never augment this interface.
- */
- interface DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_REACT_NODES {}
-
- /**
- * Represents all of the things React can render.
- *
- * Where {@link ReactElement} only represents JSX, `ReactNode` represents everything that can be rendered.
- *
- * @see {@link https://react-typescript-cheatsheet.netlify.app/docs/react-types/reactnode/ React TypeScript Cheatsheet}
- *
- * @example
- *
- * ```tsx
- * // Typing children
- * type Props = { children: ReactNode }
- *
- * const Component = ({ children }: Props) => {children}
- *
- * hello
- * ```
- *
- * @example
- *
- * ```tsx
- * // Typing a custom element
- * type Props = { customElement: ReactNode }
- *
- * const Component = ({ customElement }: Props) => {customElement}
- *
- * hello
} />
- * ```
- */
- // non-thenables need to be kept in sync with AwaitedReactNode
- type ReactNode =
- | ReactElement
- | string
- | number
- | bigint
- | Iterable
- | ReactPortal
- | boolean
- | null
- | undefined
- | DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_REACT_NODES[
- keyof DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_REACT_NODES
- ]
- | Promise;
-
- //
- // Top Level API
- // ----------------------------------------------------------------------
-
- // DOM Elements
- // TODO: generalize this to everything in `keyof ReactHTML`, not just "input"
- function createElement(
- type: "input",
- props?: InputHTMLAttributes & ClassAttributes | null,
- ...children: ReactNode[]
- ): DetailedReactHTMLElement, HTMLInputElement>;
- function createElement, T extends HTMLElement>(
- type: HTMLElementType,
- props?: ClassAttributes & P | null,
- ...children: ReactNode[]
- ): DetailedReactHTMLElement;
- function createElement
, T extends SVGElement>(
- type: SVGElementType,
- props?: ClassAttributes & P | null,
- ...children: ReactNode[]
- ): ReactSVGElement;
- function createElement, T extends Element>(
- type: string,
- props?: ClassAttributes & P | null,
- ...children: ReactNode[]
- ): DOMElement;
-
- // Custom components
-
- function createElement
(
- type: FunctionComponent
,
- props?: Attributes & P | null,
- ...children: ReactNode[]
- ): FunctionComponentElement
;
- function createElement
, C extends ComponentClass
>(
- type: ClassType
,
- props?: ClassAttributes & P | null,
- ...children: ReactNode[]
- ): CElement;
- function createElement
(
- type: FunctionComponent
| ComponentClass
| string,
- props?: Attributes & P | null,
- ...children: ReactNode[]
- ): ReactElement
;
-
- // DOM Elements
- // ReactHTMLElement
- function cloneElement
, T extends HTMLElement>(
- element: DetailedReactHTMLElement
,
- props?: P,
- ...children: ReactNode[]
- ): DetailedReactHTMLElement
;
- // ReactHTMLElement, less specific
- function cloneElement
, T extends HTMLElement>(
- element: ReactHTMLElement,
- props?: P,
- ...children: ReactNode[]
- ): ReactHTMLElement;
- // SVGElement
- function cloneElement, T extends SVGElement>(
- element: ReactSVGElement,
- props?: P,
- ...children: ReactNode[]
- ): ReactSVGElement;
- // DOM Element (has to be the last, because type checking stops at first overload that fits)
- function cloneElement
, T extends Element>(
- element: DOMElement
,
- props?: DOMAttributes & P,
- ...children: ReactNode[]
- ): DOMElement;
-
- // Custom components
- function cloneElement
(
- element: FunctionComponentElement
,
- props?: Partial
& Attributes,
- ...children: ReactNode[]
- ): FunctionComponentElement
;
- function cloneElement
>(
- element: CElement
,
- props?: Partial
& ClassAttributes,
- ...children: ReactNode[]
- ): CElement;
- function cloneElement
(
- element: ReactElement
,
- props?: Partial
& Attributes,
- ...children: ReactNode[]
- ): ReactElement
;
-
- /**
- * Describes the props accepted by a Context {@link Provider}.
- *
- * @template T The type of the value the context provides.
- */
- interface ProviderProps {
- value: T;
- children?: ReactNode | undefined;
- }
-
- /**
- * Describes the props accepted by a Context {@link Consumer}.
- *
- * @template T The type of the value the context provides.
- */
- interface ConsumerProps {
- children: (value: T) => ReactNode;
- }
-
- /**
- * An object masquerading as a component. These are created by functions
- * like {@link forwardRef}, {@link memo}, and {@link createContext}.
- *
- * In order to make TypeScript work, we pretend that they are normal
- * components.
- *
- * But they are, in fact, not callable - instead, they are objects which
- * are treated specially by the renderer.
- *
- * @template P The props the component accepts.
- */
- interface ExoticComponent {
- (props: P): ReactNode;
- readonly $$typeof: symbol;
- }
-
- /**
- * An {@link ExoticComponent} with a `displayName` property applied to it.
- *
- * @template P The props the component accepts.
- */
- interface NamedExoticComponent
extends ExoticComponent
{
- /**
- * Used in debugging messages. You might want to set it
- * explicitly if you want to display a different name for
- * debugging purposes.
- *
- * @see {@link https://legacy.reactjs.org/docs/react-component.html#displayname Legacy React Docs}
- */
- displayName?: string | undefined;
- }
-
- /**
- * An {@link ExoticComponent} with a `propTypes` property applied to it.
- *
- * @template P The props the component accepts.
- */
- interface ProviderExoticComponent
extends ExoticComponent
{
- }
-
- /**
- * Used to retrieve the type of a context object from a {@link Context}.
- *
- * @template C The context object.
- *
- * @example
- *
- * ```tsx
- * import { createContext } from 'react';
- *
- * const MyContext = createContext({ foo: 'bar' });
- *
- * type ContextType = ContextType;
- * // ContextType = { foo: string }
- * ```
- */
- type ContextType> = C extends Context ? T : never;
-
- /**
- * Wraps your components to specify the value of this context for all components inside.
- *
- * @see {@link https://react.dev/reference/react/createContext#provider React Docs}
- *
- * @example
- *
- * ```tsx
- * import { createContext } from 'react';
- *
- * const ThemeContext = createContext('light');
- *
- * function App() {
- * return (
- *
- *
- *
- * );
- * }
- * ```
- */
- type Provider = ProviderExoticComponent>;
-
- /**
- * The old way to read context, before {@link useContext} existed.
- *
- * @see {@link https://react.dev/reference/react/createContext#consumer React Docs}
- *
- * @example
- *
- * ```tsx
- * import { UserContext } from './user-context';
- *
- * function Avatar() {
- * return (
- *
- * {user =>
}
- *
- * );
- * }
- * ```
- */
- type Consumer = ExoticComponent>;
-
- /**
- * Context lets components pass information deep down without explicitly
- * passing props.
- *
- * Created from {@link createContext}
- *
- * @see {@link https://react.dev/learn/passing-data-deeply-with-context React Docs}
- * @see {@link https://react-typescript-cheatsheet.netlify.app/docs/basic/getting-started/context/ React TypeScript Cheatsheet}
- *
- * @example
- *
- * ```tsx
- * import { createContext } from 'react';
- *
- * const ThemeContext = createContext('light');
- * ```
- */
- interface Context extends Provider {
- Provider: Provider;
- Consumer: Consumer;
- /**
- * Used in debugging messages. You might want to set it
- * explicitly if you want to display a different name for
- * debugging purposes.
- *
- * @see {@link https://legacy.reactjs.org/docs/react-component.html#displayname Legacy React Docs}
- */
- displayName?: string | undefined;
- }
-
- /**
- * Lets you create a {@link Context} that components can provide or read.
- *
- * @param defaultValue The value you want the context to have when there is no matching
- * {@link Provider} in the tree above the component reading the context. This is meant
- * as a "last resort" fallback.
- *
- * @see {@link https://react.dev/reference/react/createContext#reference React Docs}
- * @see {@link https://react-typescript-cheatsheet.netlify.app/docs/basic/getting-started/context/ React TypeScript Cheatsheet}
- *
- * @example
- *
- * ```tsx
- * import { createContext } from 'react';
- *
- * const ThemeContext = createContext('light');
- * function App() {
- * return (
- *
- *
- *
- * );
- * }
- * ```
- */
- function createContext(
- // If you thought this should be optional, see
- // https://github.com/DefinitelyTyped/DefinitelyTyped/pull/24509#issuecomment-382213106
- defaultValue: T,
- ): Context;
-
- function isValidElement(object: {} | null | undefined): object is ReactElement
;
-
- const Children: {
- map(
- children: C | readonly C[],
- fn: (child: C, index: number) => T,
- ): C extends null | undefined ? C : Array>;
- forEach(children: C | readonly C[], fn: (child: C, index: number) => void): void;
- count(children: any): number;
- only(children: C): C extends any[] ? never : C;
- toArray(children: ReactNode | ReactNode[]): Array>;
- };
-
- export interface FragmentProps {
- children?: React.ReactNode;
- }
- /**
- * Lets you group elements without a wrapper node.
- *
- * @see {@link https://react.dev/reference/react/Fragment React Docs}
- *
- * @example
- *
- * ```tsx
- * import { Fragment } from 'react';
- *
- *
- * | Hello |
- * World |
- *
- * ```
- *
- * @example
- *
- * ```tsx
- * // Using the <>> shorthand syntax:
- *
- * <>
- * Hello |
- * World |
- * >
- * ```
- */
- const Fragment: ExoticComponent;
-
- /**
- * Lets you find common bugs in your components early during development.
- *
- * @see {@link https://react.dev/reference/react/StrictMode React Docs}
- *
- * @example
- *
- * ```tsx
- * import { StrictMode } from 'react';
- *
- *
- *
- *
- * ```
- */
- const StrictMode: ExoticComponent<{ children?: ReactNode | undefined }>;
-
- /**
- * The props accepted by {@link Suspense}.
- *
- * @see {@link https://react.dev/reference/react/Suspense React Docs}
- */
- interface SuspenseProps {
- children?: ReactNode | undefined;
-
- /** A fallback react tree to show when a Suspense child (like React.lazy) suspends */
- fallback?: ReactNode;
-
- /**
- * A name for this Suspense boundary for instrumentation purposes.
- * The name will help identify this boundary in React DevTools.
- */
- name?: string | undefined;
- }
-
- /**
- * Lets you display a fallback until its children have finished loading.
- *
- * @see {@link https://react.dev/reference/react/Suspense React Docs}
- *
- * @example
- *
- * ```tsx
- * import { Suspense } from 'react';
- *
- * }>
- *
- *
- * ```
- */
- const Suspense: ExoticComponent;
- const version: string;
-
- /**
- * The callback passed to {@link ProfilerProps.onRender}.
- *
- * @see {@link https://react.dev/reference/react/Profiler#onrender-callback React Docs}
- */
- type ProfilerOnRenderCallback = (
- /**
- * The string id prop of the {@link Profiler} tree that has just committed. This lets
- * you identify which part of the tree was committed if you are using multiple
- * profilers.
- *
- * @see {@link https://react.dev/reference/react/Profiler#onrender-callback React Docs}
- */
- id: string,
- /**
- * This lets you know whether the tree has just been mounted for the first time
- * or re-rendered due to a change in props, state, or hooks.
- *
- * @see {@link https://react.dev/reference/react/Profiler#onrender-callback React Docs}
- */
- phase: "mount" | "update" | "nested-update",
- /**
- * The number of milliseconds spent rendering the {@link Profiler} and its descendants
- * for the current update. This indicates how well the subtree makes use of
- * memoization (e.g. {@link memo} and {@link useMemo}). Ideally this value should decrease
- * significantly after the initial mount as many of the descendants will only need to
- * re-render if their specific props change.
- *
- * @see {@link https://react.dev/reference/react/Profiler#onrender-callback React Docs}
- */
- actualDuration: number,
- /**
- * The number of milliseconds estimating how much time it would take to re-render the entire
- * {@link Profiler} subtree without any optimizations. It is calculated by summing up the most
- * recent render durations of each component in the tree. This value estimates a worst-case
- * cost of rendering (e.g. the initial mount or a tree with no memoization). Compare
- * {@link actualDuration} against it to see if memoization is working.
- *
- * @see {@link https://react.dev/reference/react/Profiler#onrender-callback React Docs}
- */
- baseDuration: number,
- /**
- * A numeric timestamp for when React began rendering the current update.
- *
- * @see {@link https://react.dev/reference/react/Profiler#onrender-callback React Docs}
- */
- startTime: number,
- /**
- * A numeric timestamp for when React committed the current update. This value is shared
- * between all profilers in a commit, enabling them to be grouped if desirable.
- *
- * @see {@link https://react.dev/reference/react/Profiler#onrender-callback React Docs}
- */
- commitTime: number,
- ) => void;
-
- /**
- * The props accepted by {@link Profiler}.
- *
- * @see {@link https://react.dev/reference/react/Profiler React Docs}
- */
- interface ProfilerProps {
- children?: ReactNode | undefined;
- id: string;
- onRender: ProfilerOnRenderCallback;
- }
-
- /**
- * Lets you measure rendering performance of a React tree programmatically.
- *
- * @see {@link https://react.dev/reference/react/Profiler#onrender-callback React Docs}
- *
- * @example
- *
- * ```tsx
- *
- *
- *
- * ```
- */
- const Profiler: ExoticComponent;
-
- //
- // Component API
- // ----------------------------------------------------------------------
-
- type ReactInstance = Component | Element;
-
- // Base component for plain JS classes
- interface Component extends ComponentLifecycle
{}
- class Component
{
- /**
- * If set, `this.context` will be set at runtime to the current value of the given Context.
- *
- * @example
- *
- * ```ts
- * type MyContext = number
- * const Ctx = React.createContext(0)
- *
- * class Foo extends React.Component {
- * static contextType = Ctx
- * context!: React.ContextType
- * render () {
- * return <>My context's value: {this.context}>;
- * }
- * }
- * ```
- *
- * @see {@link https://react.dev/reference/react/Component#static-contexttype}
- */
- static contextType?: Context | undefined;
-
- /**
- * Ignored by React.
- * @deprecated Only kept in types for backwards compatibility. Will be removed in a future major release.
- */
- static propTypes?: any;
-
- /**
- * If using React Context, re-declare this in your class to be the
- * `React.ContextType` of your `static contextType`.
- * Should be used with type annotation or static contextType.
- *
- * @example
- * ```ts
- * static contextType = MyContext
- * // For TS pre-3.7:
- * context!: React.ContextType
- * // For TS 3.7 and above:
- * declare context: React.ContextType
- * ```
- *
- * @see {@link https://react.dev/reference/react/Component#context React Docs}
- */
- context: unknown;
-
- // Keep in sync with constructor signature of JSXElementConstructor and ComponentClass.
- constructor(props: P);
- /**
- * @param props
- * @param context value of the parent {@link https://react.dev/reference/react/Component#context Context} specified
- * in `contextType`.
- */
- // TODO: Ideally we'd infer the constructor signatur from `contextType`.
- // Might be hard to ship without breaking existing code.
- constructor(props: P, context: any);
-
- // We MUST keep setState() as a unified signature because it allows proper checking of the method return type.
- // See: https://github.com/DefinitelyTyped/DefinitelyTyped/issues/18365#issuecomment-351013257
- // Also, the ` | S` allows intellisense to not be dumbisense
- setState(
- state: ((prevState: Readonly, props: Readonly) => Pick | S | null) | (Pick | S | null),
- callback?: () => void,
- ): void;
-
- forceUpdate(callback?: () => void): void;
- render(): ReactNode;
-
- readonly props: Readonly
;
- state: Readonly;
- }
-
- class PureComponent
extends Component
{}
-
- /**
- * @deprecated Use `ClassicComponent` from `create-react-class`
- *
- * @see {@link https://legacy.reactjs.org/docs/react-without-es6.html Legacy React Docs}
- * @see {@link https://www.npmjs.com/package/create-react-class `create-react-class` on npm}
- */
- interface ClassicComponent
extends Component
{
- replaceState(nextState: S, callback?: () => void): void;
- isMounted(): boolean;
- getInitialState?(): S;
- }
-
- //
- // Class Interfaces
- // ----------------------------------------------------------------------
-
- /**
- * Represents the type of a function component. Can optionally
- * receive a type argument that represents the props the component
- * receives.
- *
- * @template P The props the component accepts.
- * @see {@link https://react-typescript-cheatsheet.netlify.app/docs/basic/getting-started/function_components React TypeScript Cheatsheet}
- * @alias for {@link FunctionComponent}
- *
- * @example
- *
- * ```tsx
- * // With props:
- * type Props = { name: string }
- *
- * const MyComponent: FC = (props) => {
- * return {props.name}
- * }
- * ```
- *
- * @example
- *
- * ```tsx
- * // Without props:
- * const MyComponentWithoutProps: FC = () => {
- * return MyComponentWithoutProps
- * }
- * ```
- */
- type FC = FunctionComponent
;
-
- /**
- * Represents the type of a function component. Can optionally
- * receive a type argument that represents the props the component
- * accepts.
- *
- * @template P The props the component accepts.
- * @see {@link https://react-typescript-cheatsheet.netlify.app/docs/basic/getting-started/function_components React TypeScript Cheatsheet}
- *
- * @example
- *
- * ```tsx
- * // With props:
- * type Props = { name: string }
- *
- * const MyComponent: FunctionComponent = (props) => {
- * return {props.name}
- * }
- * ```
- *
- * @example
- *
- * ```tsx
- * // Without props:
- * const MyComponentWithoutProps: FunctionComponent = () => {
- * return MyComponentWithoutProps
- * }
- * ```
- */
- interface FunctionComponent {
- (props: P): ReactNode | Promise;
- /**
- * Ignored by React.
- * @deprecated Only kept in types for backwards compatibility. Will be removed in a future major release.
- */
- propTypes?: any;
- /**
- * Used in debugging messages. You might want to set it
- * explicitly if you want to display a different name for
- * debugging purposes.
- *
- * @see {@link https://legacy.reactjs.org/docs/react-component.html#displayname Legacy React Docs}
- *
- * @example
- *
- * ```tsx
- *
- * const MyComponent: FC = () => {
- * return Hello!
- * }
- *
- * MyComponent.displayName = 'MyAwesomeComponent'
- * ```
- */
- displayName?: string | undefined;
- }
-
- /**
- * The type of the ref received by a {@link ForwardRefRenderFunction}.
- *
- * @see {@link ForwardRefRenderFunction}
- */
- // Making T nullable is assuming the refs will be managed by React or the component impl will write it somewhere else.
- // But this isn't necessarily true. We haven't heard complains about it yet and hopefully `forwardRef` is removed from React before we do.
- type ForwardedRef = ((instance: T | null) => void) | RefObject | null;
-
- /**
- * The type of the function passed to {@link forwardRef}. This is considered different
- * to a normal {@link FunctionComponent} because it receives an additional argument,
- *
- * @param props Props passed to the component, if any.
- * @param ref A ref forwarded to the component of type {@link ForwardedRef}.
- *
- * @template T The type of the forwarded ref.
- * @template P The type of the props the component accepts.
- *
- * @see {@link https://react-typescript-cheatsheet.netlify.app/docs/basic/getting-started/forward_and_create_ref/ React TypeScript Cheatsheet}
- * @see {@link forwardRef}
- */
- interface ForwardRefRenderFunction {
- (props: P, ref: ForwardedRef): ReactNode;
- /**
- * Used in debugging messages. You might want to set it
- * explicitly if you want to display a different name for
- * debugging purposes.
- *
- * Will show `ForwardRef(${Component.displayName || Component.name})`
- * in devtools by default, but can be given its own specific name.
- *
- * @see {@link https://legacy.reactjs.org/docs/react-component.html#displayname Legacy React Docs}
- */
- displayName?: string | undefined;
- /**
- * Ignored by React.
- * @deprecated Only kept in types for backwards compatibility. Will be removed in a future major release.
- */
- propTypes?: any;
- }
-
- /**
- * Represents a component class in React.
- *
- * @template P The props the component accepts.
- * @template S The internal state of the component.
- */
- interface ComponentClass extends StaticLifecycle
{
- // constructor signature must match React.Component
- new(
- props: P,
- /**
- * Value of the parent {@link https://react.dev/reference/react/Component#context Context} specified
- * in `contextType`.
- */
- context?: any,
- ): Component
;
- /**
- * Ignored by React.
- * @deprecated Only kept in types for backwards compatibility. Will be removed in a future major release.
- */
- propTypes?: any;
- contextType?: Context | undefined;
- defaultProps?: Partial | undefined;
- /**
- * Used in debugging messages. You might want to set it
- * explicitly if you want to display a different name for
- * debugging purposes.
- *
- * @see {@link https://legacy.reactjs.org/docs/react-component.html#displayname Legacy React Docs}
- */
- displayName?: string | undefined;
- }
-
- /**
- * @deprecated Use `ClassicComponentClass` from `create-react-class`
- *
- * @see {@link https://legacy.reactjs.org/docs/react-without-es6.html Legacy React Docs}
- * @see {@link https://www.npmjs.com/package/create-react-class `create-react-class` on npm}
- */
- interface ClassicComponentClass
extends ComponentClass
{
- new(props: P): ClassicComponent
;
- getDefaultProps?(): P;
- }
-
- /**
- * Used in {@link createElement} and {@link createFactory} to represent
- * a class.
- *
- * An intersection type is used to infer multiple type parameters from
- * a single argument, which is useful for many top-level API defs.
- * See {@link https://github.com/Microsoft/TypeScript/issues/7234 this GitHub issue}
- * for more info.
- */
- type ClassType
, C extends ComponentClass
> =
- & C
- & (new(props: P, context: any) => T);
-
- //
- // Component Specs and Lifecycle
- // ----------------------------------------------------------------------
-
- // This should actually be something like `Lifecycle
| DeprecatedLifecycle
`,
- // as React will _not_ call the deprecated lifecycle methods if any of the new lifecycle
- // methods are present.
- interface ComponentLifecycle
extends NewLifecycle
, DeprecatedLifecycle
{
- /**
- * Called immediately after a component is mounted. Setting state here will trigger re-rendering.
- */
- componentDidMount?(): void;
- /**
- * Called to determine whether the change in props and state should trigger a re-render.
- *
- * `Component` always returns true.
- * `PureComponent` implements a shallow comparison on props and state and returns true if any
- * props or states have changed.
- *
- * If false is returned, {@link Component.render}, `componentWillUpdate`
- * and `componentDidUpdate` will not be called.
- */
- shouldComponentUpdate?(nextProps: Readonly
, nextState: Readonly, nextContext: any): boolean;
- /**
- * Called immediately before a component is destroyed. Perform any necessary cleanup in this method, such as
- * cancelled network requests, or cleaning up any DOM elements created in `componentDidMount`.
- */
- componentWillUnmount?(): void;
- /**
- * Catches exceptions generated in descendant components. Unhandled exceptions will cause
- * the entire component tree to unmount.
- */
- componentDidCatch?(error: Error, errorInfo: ErrorInfo): void;
- }
-
- // Unfortunately, we have no way of declaring that the component constructor must implement this
- interface StaticLifecycle
{
- getDerivedStateFromProps?: GetDerivedStateFromProps
| undefined;
- getDerivedStateFromError?: GetDerivedStateFromError
| undefined;
- }
-
- type GetDerivedStateFromProps
=
- /**
- * Returns an update to a component's state based on its new props and old state.
- *
- * Note: its presence prevents any of the deprecated lifecycle methods from being invoked
- */
- (nextProps: Readonly
, prevState: S) => Partial | null;
-
- type GetDerivedStateFromError
=
- /**
- * This lifecycle is invoked after an error has been thrown by a descendant component.
- * It receives the error that was thrown as a parameter and should return a value to update state.
- *
- * Note: its presence prevents any of the deprecated lifecycle methods from being invoked
- */
- (error: any) => Partial | null;
-
- // This should be "infer SS" but can't use it yet
- interface NewLifecycle
{
- /**
- * Runs before React applies the result of {@link Component.render render} to the document, and
- * returns an object to be given to {@link componentDidUpdate}. Useful for saving
- * things such as scroll position before {@link Component.render render} causes changes to it.
- *
- * Note: the presence of this method prevents any of the deprecated
- * lifecycle events from running.
- */
- getSnapshotBeforeUpdate?(prevProps: Readonly
, prevState: Readonly): SS | null;
- /**
- * Called immediately after updating occurs. Not called for the initial render.
- *
- * The snapshot is only present if {@link getSnapshotBeforeUpdate} is present and returns non-null.
- */
- componentDidUpdate?(prevProps: Readonly
, prevState: Readonly, snapshot?: SS): void;
- }
-
- interface DeprecatedLifecycle
{
- /**
- * Called immediately before mounting occurs, and before {@link Component.render}.
- * Avoid introducing any side-effects or subscriptions in this method.
- *
- * Note: the presence of {@link NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate}
- * or {@link StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps} prevents
- * this from being invoked.
- *
- * @deprecated 16.3, use {@link ComponentLifecycle.componentDidMount componentDidMount} or the constructor instead; will stop working in React 17
- * @see {@link https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html#initializing-state}
- * @see {@link https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html#gradual-migration-path}
- */
- componentWillMount?(): void;
- /**
- * Called immediately before mounting occurs, and before {@link Component.render}.
- * Avoid introducing any side-effects or subscriptions in this method.
- *
- * This method will not stop working in React 17.
- *
- * Note: the presence of {@link NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate}
- * or {@link StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps} prevents
- * this from being invoked.
- *
- * @deprecated 16.3, use {@link ComponentLifecycle.componentDidMount componentDidMount} or the constructor instead
- * @see {@link https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html#initializing-state}
- * @see {@link https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html#gradual-migration-path}
- */
- UNSAFE_componentWillMount?(): void;
- /**
- * Called when the component may be receiving new props.
- * React may call this even if props have not changed, so be sure to compare new and existing
- * props if you only want to handle changes.
- *
- * Calling {@link Component.setState} generally does not trigger this method.
- *
- * Note: the presence of {@link NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate}
- * or {@link StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps} prevents
- * this from being invoked.
- *
- * @deprecated 16.3, use static {@link StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps} instead; will stop working in React 17
- * @see {@link https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html#updating-state-based-on-props}
- * @see {@link https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html#gradual-migration-path}
- */
- componentWillReceiveProps?(nextProps: Readonly
, nextContext: any): void;
- /**
- * Called when the component may be receiving new props.
- * React may call this even if props have not changed, so be sure to compare new and existing
- * props if you only want to handle changes.
- *
- * Calling {@link Component.setState} generally does not trigger this method.
- *
- * This method will not stop working in React 17.
- *
- * Note: the presence of {@link NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate}
- * or {@link StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps} prevents
- * this from being invoked.
- *
- * @deprecated 16.3, use static {@link StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps} instead
- * @see {@link https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html#updating-state-based-on-props}
- * @see {@link https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html#gradual-migration-path}
- */
- UNSAFE_componentWillReceiveProps?(nextProps: Readonly
, nextContext: any): void;
- /**
- * Called immediately before rendering when new props or state is received. Not called for the initial render.
- *
- * Note: You cannot call {@link Component.setState} here.
- *
- * Note: the presence of {@link NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate}
- * or {@link StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps} prevents
- * this from being invoked.
- *
- * @deprecated 16.3, use getSnapshotBeforeUpdate instead; will stop working in React 17
- * @see {@link https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html#reading-dom-properties-before-an-update}
- * @see {@link https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html#gradual-migration-path}
- */
- componentWillUpdate?(nextProps: Readonly
, nextState: Readonly, nextContext: any): void;
- /**
- * Called immediately before rendering when new props or state is received. Not called for the initial render.
- *
- * Note: You cannot call {@link Component.setState} here.
- *
- * This method will not stop working in React 17.
- *
- * Note: the presence of {@link NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate}
- * or {@link StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps} prevents
- * this from being invoked.
- *
- * @deprecated 16.3, use getSnapshotBeforeUpdate instead
- * @see {@link https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html#reading-dom-properties-before-an-update}
- * @see {@link https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html#gradual-migration-path}
- */
- UNSAFE_componentWillUpdate?(nextProps: Readonly
, nextState: Readonly, nextContext: any): void;
- }
-
- function createRef(): RefObject;
-
- /**
- * The type of the component returned from {@link forwardRef}.
- *
- * @template P The props the component accepts, if any.
- *
- * @see {@link ExoticComponent}
- */
- interface ForwardRefExoticComponent extends NamedExoticComponent
{
- /**
- * Ignored by React.
- * @deprecated Only kept in types for backwards compatibility. Will be removed in a future major release.
- */
- propTypes?: any;
- }
-
- /**
- * Lets your component expose a DOM node to a parent component
- * using a ref.
- *
- * @see {@link https://react.dev/reference/react/forwardRef React Docs}
- * @see {@link https://react-typescript-cheatsheet.netlify.app/docs/basic/getting-started/forward_and_create_ref/ React TypeScript Cheatsheet}
- *
- * @param render See the {@link ForwardRefRenderFunction}.
- *
- * @template T The type of the DOM node.
- * @template P The props the component accepts, if any.
- *
- * @example
- *
- * ```tsx
- * interface Props {
- * children?: ReactNode;
- * type: "submit" | "button";
- * }
- *
- * export const FancyButton = forwardRef((props, ref) => (
- *
- * ));
- * ```
- */
- function forwardRef(
- render: ForwardRefRenderFunction>,
- ): ForwardRefExoticComponent & RefAttributes>;
-
- /**
- * Omits the 'ref' attribute from the given props object.
- *
- * @template Props The props object type.
- */
- type PropsWithoutRef =
- // Omit would not be sufficient for this. We'd like to avoid unnecessary mapping and need a distributive conditional to support unions.
- // see: https://www.typescriptlang.org/docs/handbook/2/conditional-types.html#distributive-conditional-types
- // https://github.com/Microsoft/TypeScript/issues/28339
- Props extends any ? ("ref" extends keyof Props ? Omit : Props) : Props;
- /**
- * Ensures that the props do not include string ref, which cannot be forwarded
- * @deprecated Use `Props` directly. `PropsWithRef` is just an alias for `Props`
- */
- type PropsWithRef = Props;
-
- type PropsWithChildren = P & { children?: ReactNode | undefined };
-
- /**
- * Used to retrieve the props a component accepts. Can either be passed a string,
- * indicating a DOM element (e.g. 'div', 'span', etc.) or the type of a React
- * component.
- *
- * It's usually better to use {@link ComponentPropsWithRef} or {@link ComponentPropsWithoutRef}
- * instead of this type, as they let you be explicit about whether or not to include
- * the `ref` prop.
- *
- * @see {@link https://react-typescript-cheatsheet.netlify.app/docs/react-types/componentprops/ React TypeScript Cheatsheet}
- *
- * @example
- *
- * ```tsx
- * // Retrieves the props an 'input' element accepts
- * type InputProps = React.ComponentProps<'input'>;
- * ```
- *
- * @example
- *
- * ```tsx
- * const MyComponent = (props: { foo: number, bar: string }) =>
;
- *
- * // Retrieves the props 'MyComponent' accepts
- * type MyComponentProps = React.ComponentProps;
- * ```
- */
- type ComponentProps> = T extends
- JSXElementConstructor ? Props
- : T extends keyof JSX.IntrinsicElements ? JSX.IntrinsicElements[T]
- : {};
-
- /**
- * Used to retrieve the props a component accepts with its ref. Can either be
- * passed a string, indicating a DOM element (e.g. 'div', 'span', etc.) or the
- * type of a React component.
- *
- * @see {@link https://react-typescript-cheatsheet.netlify.app/docs/react-types/componentprops/ React TypeScript Cheatsheet}
- *
- * @example
- *
- * ```tsx
- * // Retrieves the props an 'input' element accepts
- * type InputProps = React.ComponentPropsWithRef<'input'>;
- * ```
- *
- * @example
- *
- * ```tsx
- * const MyComponent = (props: { foo: number, bar: string }) => ;
- *
- * // Retrieves the props 'MyComponent' accepts
- * type MyComponentPropsWithRef = React.ComponentPropsWithRef;
- * ```
- */
- type ComponentPropsWithRef = T extends JSXElementConstructor
- // If it's a class i.e. newable we're dealing with a class component
- ? T extends abstract new(args: any) => any ? PropsWithoutRef & RefAttributes>
- : Props
- : ComponentProps;
- /**
- * Used to retrieve the props a custom component accepts with its ref.
- *
- * Unlike {@link ComponentPropsWithRef}, this only works with custom
- * components, i.e. components you define yourself. This is to improve
- * type-checking performance.
- *
- * @example
- *
- * ```tsx
- * const MyComponent = (props: { foo: number, bar: string }) => ;
- *
- * // Retrieves the props 'MyComponent' accepts
- * type MyComponentPropsWithRef = React.CustomComponentPropsWithRef;
- * ```
- */
- type CustomComponentPropsWithRef = T extends JSXElementConstructor
- // If it's a class i.e. newable we're dealing with a class component
- ? T extends abstract new(args: any) => any ? PropsWithoutRef & RefAttributes>
- : Props
- : never;
-
- /**
- * Used to retrieve the props a component accepts without its ref. Can either be
- * passed a string, indicating a DOM element (e.g. 'div', 'span', etc.) or the
- * type of a React component.
- *
- * @see {@link https://react-typescript-cheatsheet.netlify.app/docs/react-types/componentprops/ React TypeScript Cheatsheet}
- *
- * @example
- *
- * ```tsx
- * // Retrieves the props an 'input' element accepts
- * type InputProps = React.ComponentPropsWithoutRef<'input'>;
- * ```
- *
- * @example
- *
- * ```tsx
- * const MyComponent = (props: { foo: number, bar: string }) => ;
- *
- * // Retrieves the props 'MyComponent' accepts
- * type MyComponentPropsWithoutRef = React.ComponentPropsWithoutRef;
- * ```
- */
- type ComponentPropsWithoutRef = PropsWithoutRef>;
-
- /**
- * Retrieves the type of the 'ref' prop for a given component type or tag name.
- *
- * @template C The component type.
- *
- * @example
- *
- * ```tsx
- * type MyComponentRef = React.ComponentRef;
- * ```
- *
- * @example
- *
- * ```tsx
- * type DivRef = React.ComponentRef<'div'>;
- * ```
- */
- type ComponentRef = ComponentPropsWithRef extends RefAttributes ? Method
- : never;
-
- // will show `Memo(${Component.displayName || Component.name})` in devtools by default,
- // but can be given its own specific name
- type MemoExoticComponent> = NamedExoticComponent> & {
- readonly type: T;
- };
-
- /**
- * Lets you skip re-rendering a component when its props are unchanged.
- *
- * @see {@link https://react.dev/reference/react/memo React Docs}
- *
- * @param Component The component to memoize.
- * @param propsAreEqual A function that will be used to determine if the props have changed.
- *
- * @example
- *
- * ```tsx
- * import { memo } from 'react';
- *
- * const SomeComponent = memo(function SomeComponent(props: { foo: string }) {
- * // ...
- * });
- * ```
- */
- function memo(
- Component: FunctionComponent
,
- propsAreEqual?: (prevProps: Readonly
, nextProps: Readonly
) => boolean,
- ): NamedExoticComponent
;
- function memo>(
- Component: T,
- propsAreEqual?: (prevProps: Readonly>, nextProps: Readonly>) => boolean,
- ): MemoExoticComponent;
-
- interface LazyExoticComponent>
- extends ExoticComponent>
- {
- readonly _result: T;
- }
-
- /**
- * Lets you defer loading a component’s code until it is rendered for the first time.
- *
- * @see {@link https://react.dev/reference/react/lazy React Docs}
- *
- * @param load A function that returns a `Promise` or another thenable (a `Promise`-like object with a
- * then method). React will not call `load` until the first time you attempt to render the returned
- * component. After React first calls load, it will wait for it to resolve, and then render the
- * resolved value’s `.default` as a React component. Both the returned `Promise` and the `Promise`’s
- * resolved value will be cached, so React will not call load more than once. If the `Promise` rejects,
- * React will throw the rejection reason for the nearest Error Boundary to handle.
- *
- * @example
- *
- * ```tsx
- * import { lazy } from 'react';
- *
- * const MarkdownPreview = lazy(() => import('./MarkdownPreview.js'));
- * ```
- */
- function lazy>(
- load: () => Promise<{ default: T }>,
- ): LazyExoticComponent;
-
- //
- // React Hooks
- // ----------------------------------------------------------------------
-
- /**
- * The instruction passed to a {@link Dispatch} function in {@link useState}
- * to tell React what the next value of the {@link useState} should be.
- *
- * Often found wrapped in {@link Dispatch}.
- *
- * @template S The type of the state.
- *
- * @example
- *
- * ```tsx
- * // This return type correctly represents the type of
- * // `setCount` in the example below.
- * const useCustomState = (): Dispatch> => {
- * const [count, setCount] = useState(0);
- *
- * return setCount;
- * }
- * ```
- */
- type SetStateAction = S | ((prevState: S) => S);
-
- /**
- * A function that can be used to update the state of a {@link useState}
- * or {@link useReducer} hook.
- */
- type Dispatch = (value: A) => void;
- /**
- * A {@link Dispatch} function can sometimes be called without any arguments.
- */
- type DispatchWithoutAction = () => void;
- // Limit the reducer to accept only 0 or 1 action arguments
- // eslint-disable-next-line @definitelytyped/no-single-element-tuple-type
- type AnyActionArg = [] | [any];
- // Get the dispatch type from the reducer arguments (captures optional action argument correctly)
- type ActionDispatch = (...args: ActionArg) => void;
- // Unlike redux, the actions _can_ be anything
- type Reducer = (prevState: S, action: A) => S;
- // If useReducer accepts a reducer without action, dispatch may be called without any parameters.
- type ReducerWithoutAction = (prevState: S) => S;
- // types used to try and prevent the compiler from reducing S
- // to a supertype common with the second argument to useReducer()
- type ReducerState> = R extends Reducer ? S : never;
- type DependencyList = readonly unknown[];
-
- // NOTE: callbacks are _only_ allowed to return either void, or a destructor.
- type EffectCallback = () => void | Destructor;
-
- /**
- * @deprecated Use `RefObject` instead.
- */
- interface MutableRefObject {
- current: T;
- }
-
- // This will technically work if you give a Consumer or Provider but it's deprecated and warns
- /**
- * Accepts a context object (the value returned from `React.createContext`) and returns the current
- * context value, as given by the nearest context provider for the given context.
- *
- * @version 16.8.0
- * @see {@link https://react.dev/reference/react/useContext}
- */
- function useContext(context: Context /*, (not public API) observedBits?: number|boolean */): T;
- /**
- * Returns a stateful value, and a function to update it.
- *
- * @version 16.8.0
- * @see {@link https://react.dev/reference/react/useState}
- */
- function useState(initialState: S | (() => S)): [S, Dispatch>];
- // convenience overload when first argument is omitted
- /**
- * Returns a stateful value, and a function to update it.
- *
- * @version 16.8.0
- * @see {@link https://react.dev/reference/react/useState}
- */
- function useState(): [S | undefined, Dispatch>];
- /**
- * An alternative to `useState`.
- *
- * `useReducer` is usually preferable to `useState` when you have complex state logic that involves
- * multiple sub-values. It also lets you optimize performance for components that trigger deep
- * updates because you can pass `dispatch` down instead of callbacks.
- *
- * @version 16.8.0
- * @see {@link https://react.dev/reference/react/useReducer}
- */
- function useReducer(
- reducer: (prevState: S, ...args: A) => S,
- initialState: S,
- ): [S, ActionDispatch];
- /**
- * An alternative to `useState`.
- *
- * `useReducer` is usually preferable to `useState` when you have complex state logic that involves
- * multiple sub-values. It also lets you optimize performance for components that trigger deep
- * updates because you can pass `dispatch` down instead of callbacks.
- *
- * @version 16.8.0
- * @see {@link https://react.dev/reference/react/useReducer}
- */
- function useReducer(
- reducer: (prevState: S, ...args: A) => S,
- initialArg: I,
- init: (i: I) => S,
- ): [S, ActionDispatch];
- /**
- * `useRef` returns a mutable ref object whose `.current` property is initialized to the passed argument
- * (`initialValue`). The returned object will persist for the full lifetime of the component.
- *
- * Note that `useRef()` is useful for more than the `ref` attribute. It’s handy for keeping any mutable
- * value around similar to how you’d use instance fields in classes.
- *
- * @version 16.8.0
- * @see {@link https://react.dev/reference/react/useRef}
- */
- function useRef(initialValue: T): RefObject;
- // convenience overload for refs given as a ref prop as they typically start with a null value
- /**
- * `useRef` returns a mutable ref object whose `.current` property is initialized to the passed argument
- * (`initialValue`). The returned object will persist for the full lifetime of the component.
- *
- * Note that `useRef()` is useful for more than the `ref` attribute. It’s handy for keeping any mutable
- * value around similar to how you’d use instance fields in classes.
- *
- * @version 16.8.0
- * @see {@link https://react.dev/reference/react/useRef}
- */
- function useRef(initialValue: T | null): RefObject;
- // convenience overload for undefined initialValue
- /**
- * `useRef` returns a mutable ref object whose `.current` property is initialized to the passed argument
- * (`initialValue`). The returned object will persist for the full lifetime of the component.
- *
- * Note that `useRef()` is useful for more than the `ref` attribute. It’s handy for keeping any mutable
- * value around similar to how you’d use instance fields in classes.
- *
- * @version 16.8.0
- * @see {@link https://react.dev/reference/react/useRef}
- */
- function useRef(initialValue: T | undefined): RefObject;
- /**
- * The signature is identical to `useEffect`, but it fires synchronously after all DOM mutations.
- * Use this to read layout from the DOM and synchronously re-render. Updates scheduled inside
- * `useLayoutEffect` will be flushed synchronously, before the browser has a chance to paint.
- *
- * Prefer the standard `useEffect` when possible to avoid blocking visual updates.
- *
- * If you’re migrating code from a class component, `useLayoutEffect` fires in the same phase as
- * `componentDidMount` and `componentDidUpdate`.
- *
- * @version 16.8.0
- * @see {@link https://react.dev/reference/react/useLayoutEffect}
- */
- function useLayoutEffect(effect: EffectCallback, deps?: DependencyList): void;
- /**
- * Accepts a function that contains imperative, possibly effectful code.
- *
- * @param effect Imperative function that can return a cleanup function
- * @param deps If present, effect will only activate if the values in the list change.
- *
- * @version 16.8.0
- * @see {@link https://react.dev/reference/react/useEffect}
- */
- function useEffect(effect: EffectCallback, deps?: DependencyList): void;
- /**
- * @see {@link https://react.dev/reference/react/useEffectEvent `useEffectEvent()` documentation}
- * @version 19.2.0
- */
- // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
- export function useEffectEvent(callback: T): T;
- // NOTE: this does not accept strings, but this will have to be fixed by removing strings from type Ref
- /**
- * `useImperativeHandle` customizes the instance value that is exposed to parent components when using
- * `ref`. As always, imperative code using refs should be avoided in most cases.
- *
- * @version 16.8.0
- * @see {@link https://react.dev/reference/react/useImperativeHandle}
- */
- function useImperativeHandle(ref: Ref | undefined, init: () => R, deps?: DependencyList): void;
- // I made 'inputs' required here and in useMemo as there's no point to memoizing without the memoization key
- // useCallback(X) is identical to just using X, useMemo(() => Y) is identical to just using Y.
- /**
- * `useCallback` will return a memoized version of the callback that only changes if one of the `inputs`
- * has changed.
- *
- * @version 16.8.0
- * @see {@link https://react.dev/reference/react/useCallback}
- */
- // A specific function type would not trigger implicit any.
- // See https://github.com/DefinitelyTyped/DefinitelyTyped/issues/52873#issuecomment-845806435 for a comparison between `Function` and more specific types.
- // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
- function useCallback(callback: T, deps: DependencyList): T;
- /**
- * `useMemo` will only recompute the memoized value when one of the `deps` has changed.
- *
- * @version 16.8.0
- * @see {@link https://react.dev/reference/react/useMemo}
- */
- // allow undefined, but don't make it optional as that is very likely a mistake
- function useMemo(factory: () => T, deps: DependencyList): T;
- /**
- * `useDebugValue` can be used to display a label for custom hooks in React DevTools.
- *
- * NOTE: We don’t recommend adding debug values to every custom hook.
- * It’s most valuable for custom hooks that are part of shared libraries.
- *
- * @version 16.8.0
- * @see {@link https://react.dev/reference/react/useDebugValue}
- */
- // the name of the custom hook is itself derived from the function name at runtime:
- // it's just the function name without the "use" prefix.
- function useDebugValue(value: T, format?: (value: T) => any): void;
-
- export type TransitionFunction = () => VoidOrUndefinedOnly | Promise;
- // strange definition to allow vscode to show documentation on the invocation
- export interface TransitionStartFunction {
- /**
- * State updates caused inside the callback are allowed to be deferred.
- *
- * **If some state update causes a component to suspend, that state update should be wrapped in a transition.**
- *
- * @param callback A function which causes state updates that can be deferred.
- */
- (callback: TransitionFunction): void;
- }
-
- /**
- * Returns a deferred version of the value that may “lag behind” it.
- *
- * This is commonly used to keep the interface responsive when you have something that renders immediately
- * based on user input and something that needs to wait for a data fetch.
- *
- * A good example of this is a text input.
- *
- * @param value The value that is going to be deferred
- * @param initialValue A value to use during the initial render of a component. If this option is omitted, `useDeferredValue` will not defer during the initial render, because there’s no previous version of `value` that it can render instead.
- *
- * @see {@link https://react.dev/reference/react/useDeferredValue}
- */
- export function useDeferredValue(value: T, initialValue?: T): T;
-
- /**
- * Allows components to avoid undesirable loading states by waiting for content to load
- * before transitioning to the next screen. It also allows components to defer slower,
- * data fetching updates until subsequent renders so that more crucial updates can be
- * rendered immediately.
- *
- * The `useTransition` hook returns two values in an array.
- *
- * The first is a boolean, React’s way of informing us whether we’re waiting for the transition to finish.
- * The second is a function that takes a callback. We can use it to tell React which state we want to defer.
- *
- * **If some state update causes a component to suspend, that state update should be wrapped in a transition.**
- *
- * @see {@link https://react.dev/reference/react/useTransition}
- */
- export function useTransition(): [boolean, TransitionStartFunction];
-
- /**
- * Similar to `useTransition` but allows uses where hooks are not available.
- *
- * @param callback A function which causes state updates that can be deferred.
- */
- export function startTransition(scope: TransitionFunction): void;
-
- /**
- * Wrap any code rendering and triggering updates to your components into `act()` calls.
- *
- * Ensures that the behavior in your tests matches what happens in the browser
- * more closely by executing pending `useEffect`s before returning. This also
- * reduces the amount of re-renders done.
- *
- * @param callback A synchronous, void callback that will execute as a single, complete React commit.
- *
- * @see https://reactjs.org/blog/2019/02/06/react-v16.8.0.html#testing-hooks
- */
- // NOTES
- // - the order of these signatures matters - typescript will check the signatures in source order.
- // If the `() => VoidOrUndefinedOnly` signature is first, it'll erroneously match a Promise returning function for users with
- // `strictNullChecks: false`.
- // - VoidOrUndefinedOnly is there to forbid any non-void return values for users with `strictNullChecks: true`
- // While act does always return Thenable, if a void function is passed, we pretend the return value is also void to not trigger dangling Promise lint rules.
- export function act(callback: () => VoidOrUndefinedOnly): void;
- export function act(callback: () => T | Promise): Promise;
-
- export function useId(): string;
-
- /**
- * @param effect Imperative function that can return a cleanup function
- * @param deps If present, effect will only activate if the values in the list change.
- *
- * @see {@link https://github.com/facebook/react/pull/21913}
- */
- export function useInsertionEffect(effect: EffectCallback, deps?: DependencyList): void;
-
- /**
- * @param subscribe
- * @param getSnapshot
- *
- * @see {@link https://github.com/reactwg/react-18/discussions/86}
- */
- // keep in sync with `useSyncExternalStore` from `use-sync-external-store`
- export function useSyncExternalStore(
- subscribe: (onStoreChange: () => void) => () => void,
- getSnapshot: () => Snapshot,
- getServerSnapshot?: () => Snapshot,
- ): Snapshot;
-
- export function useOptimistic(
- passthrough: State,
- ): [State, (action: State | ((pendingState: State) => State)) => void];
- export function useOptimistic(
- passthrough: State,
- reducer: (state: State, action: Action) => State,
- ): [State, (action: Action) => void];
-
- interface UntrackedReactPromise extends PromiseLike {
- status?: void;
- }
-
- export interface PendingReactPromise extends PromiseLike {
- status: "pending";
- }
-
- export interface FulfilledReactPromise extends PromiseLike {
- status: "fulfilled";
- value: T;
- }
-
- export interface RejectedReactPromise extends PromiseLike {
- status: "rejected";
- reason: unknown;
- }
-
- export type ReactPromise =
- | UntrackedReactPromise
- | PendingReactPromise
- | FulfilledReactPromise
- | RejectedReactPromise;
-
- export type Usable = ReactPromise | Context;
-
- export function use(usable: Usable): T;
-
- export function useActionState(
- action: (state: Awaited) => State | Promise,
- initialState: Awaited,
- permalink?: string,
- ): [state: Awaited, dispatch: () => void, isPending: boolean];
- export function useActionState(
- action: (state: Awaited, payload: Payload) => State | Promise,
- initialState: Awaited,
- permalink?: string,
- ): [state: Awaited, dispatch: (payload: Payload) => void, isPending: boolean];
-
- // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
- export function cache