Skip to main content
Version: v7

Hooks

Refer to the TypeScript reference page for information about the types and interfaces referenced below.

These Hooks are used internally by React Query Builder.

Component logic

The core logic of each component is encapsulated in a reusable Hook. Each main component is itself little more than a call to its respective Hook and the JSX that utilizes the properties in the returned object. This enables the creation of a custom presentation layer without having to copy all the code from the default components.

tip

The @react-querybuilder/native package is a good example of this concept. It calls the Hooks from its own query builder, rule group, and rule components, but nests the sub-components within React Native View elements instead of HTML div elements like the react-querybuilder components.

useQueryBuilderSetup

Called by the QueryBuilder component. Merges props and context values with the defaults and generates actions.

function useQueryBuilderSetup(props: QueryBuilderProps): {
qbId: qbId.current;
rqbContext: ReturnType<typeof useMergedContext>;
fields: OptionList<Field>;
fieldMap: Record<string, Field>;
combinators: OptionList<Combinator>;
getOperatorsMain: (field: string) => OptionList<Operator>;
getRuleDefaultOperator: (field: string) => string;
getValueEditorTypeMain: (field: string, operator: string) => ValueEditorType;
getValueSourcesMain: (field: string, operator: string) => ValueSources;
getValuesMain: (field: string, operator: string) => OptionList;
getRuleDefaultValue: (rule: RuleType) => any;
getInputTypeMain: (field: string, operator: string) => string;
createRule: () => RuleType;
createRuleGroup: () => RuleGroupTypeAny;
};

useQueryBuilderSchema

Called by the internal component rendered by QueryBuilder. Returns everything needed to render a wrapper element (e.g., <div>) and the root RuleGroup element based on the provided props and the result from useQueryBuilderSetup. Generates an id for each rule and group in the query hierarchy that doesn't already have one.

This Hook must be called from a descendant component of QueryBuilderStateProvider. See QueryBuilder source code for an example.

function useQueryBuilderSchema(
props: QueryBuilderProps,
setup: ReturnType<typeof useQueryBuilderSetup>
): QueryBuilderProps & {
actions: QueryActions;
rootGroup: RuleGroupTypeAny;
rootGroupDisabled: RuleGroupTypeAny;
queryDisabled: boolean;
rqbContext: ReturnType<typeof useMergedContext>;
schema: Schema;
translations: TranslationsFull;
wrapperClassName: string;
dndEnabledAttr: 'enabled' | 'disabled';
inlineCombinatorsAttr: 'enabled' | 'disabled';
combinatorPropObject: Pick<RuleGroupProps, 'combinator'>;
};

useRuleGroup

Called by the RuleGroup component. See source code for returned properties.

function useRuleGroup(props: RuleGroupProps): {
// See source code for returned properties
};

useRule

Called by the Rule component. See source code for returned properties.

function useRule(props: RuleProps): {
// See source code for returned properties
};

useValueEditor

Called by the ValueEditor component. Accepts an object with a subset of ValueEditorProps and returns the value as an array and a multi-value handler.

function useValueEditor(
props: Pick<
ValueEditorProps,
| 'handleOnChange'
| 'inputType'
| 'operator'
| 'value'
| 'listsAsArrays'
| 'type'
| 'values'
| 'parseNumbers'
| 'skipHook'
>
): { valueAsArray: any[]; multiValueHandler: (val: string, idx: number) => void };

This Hook updates the value as a side effect if the following conditions are true:

  • skipHook is false (the value editors in the compatibility packages set this to true to avoid infinite loops)
  • inputType is "number"
  • operator is something other than "between", "notBetween", "in", or "notIn"
  • valueEditorType is not "multiselect"
  • value is an array or a string containing a comma (,).

If all of these conditions are met, handleOnChange will be called with the first element of the array, or any characters before the first comma if value is a string.

useValueSelector

Called by the ValueSelector component. Transforms the given value into an array when appropriate and provides a memoized change handler.

function useValueSelector(
props: Pick<ValueSelectorProps, 'handleOnChange' | 'listsAsArrays' | 'multiple' | 'value'>
): {
onChange: (v: string | string[]) => void;
val?: string | any[];
};

useShiftActions

Used by the ShiftActions component. Generates shiftUp and shiftDown methods to move a rule/group up or down, respectively, in the query hierarchy, as well as shiftUpDisabled/shiftDownDisabled to indicate whether either button should be disabled.

function useShiftActions(
props: { path: Path } & Pick<Schema, 'combinators' | 'dispatchQuery' | 'getQuery'>
): {
shiftDown: () => void;
shiftDownDisabled: boolean;
shiftUp: () => void;
shiftUpDisabled: boolean;
};

useSelectElementChangeHandler

Used by the ValueSelector component. Returns a memoized change handler specifically for HTML <select /> elements.

function useSelectElementChangeHandler(props: {
multiple?: boolean;
onChange: (v: string | string[]) => void;
}): (e: ChangeEvent<HTMLSelectElement>) => void;

useStopEventPropagation

Used by the default Rule and RuleGroup components to prevent default behavior and stop propagation of events (e.g., a MouseEvent after clicking a <button>). Takes an object where the value of each key is a function taking MouseEvent and context parameters; returns the same object with the respective functions having the same signature but calling event.preventDefault() and event.stopPropagation() first.

function useStopEventPropagation(
methods: Record<string, (event: React.MouseEvent, context: any) => void>
): Record<string, (event: React.MouseEvent, context: any) => void>;

This hook is not used in the Rule and RuleGroup components used/exported by @react-querybuilder/native.

Redux state access

React Query Builder uses a custom React context for its Redux implementation, so it shouldn't interfere with existing Redux stores.

useQueryBuilderDispatch

Gets the dispatch function from the React Query Builder Redux store.

function useQueryBuilderDispatch(): ThunkDispatch<RqbState> & Dispatch;

useQueryBuilderSelector

Passes the current state from the React Query Builder Redux store to a selector that retrieves the query from the state object. To generate such a selector, call getQuerySelectorById from any custom component, passing it the qbId from the schema prop.

function useQueryBuilderSelector(selector: (state: RqbState) => RuleGroupTypeAny): RuleGroupTypeAny;

Example:

const CustomValueEditor = (props: ValueEditorProps) => {
const fullQuery = useQueryBuilderSelector(getQuerySelectorById(props.schema.qbId));
// ...
};

useQueryBuilderStore

Gets the full React Query Builder Redux store. Not recommended for general use.

function useQueryBuilderStore(): Store<RqbState>;

Other utilities

useMergedContext

Merges the values inherited from the nearest ancestor QueryBuilderContext.Provider with the current component's props. For controlClassnames, controlElements, and translations, options that are not defined through either context or props will fall back to the defaults.

function useMergedContext(props: QueryBuilderContextProps): QueryBuilderContextProps;

usePreferProp

Given a default value, a prop value, and a context value (all boolean or undefined), returns the first one that is not undefined in the order of (1) prop, (2) context, (3) default.

function usePreferProp(default: boolean, prop?: boolean, context?: boolean): boolean;

usePrevious

Returns the value of a prop or state variable from the previous render.

function usePrevious<T>(prop: T): T | null;

Internal

These Hooks log error messages to the console in certain situations (and only in "development" mode). They encourage correct usage of React Query Builder and are not intended to be used in custom components.

useControlledOrUncontrolled

Logs an error to the console if any of the following are true:

  • Both query and defaultQuery props are defined.
  • The query prop is defined during one render and undefined in a subsequent render.
  • The query prop is undefined during one render and defined in a subsequent render.

useDeprecatedProps

Logs an error to the console if any of the following are true:

  • QueryBuilder is rendered with independentCombinators prop (see Independent combinators)
  • RuleGroup is rendered with combinator or rules props (deprecated in favor of ruleGroup)
  • Rule is rendered with field, operator, or value props (deprecated in favor of rule)

useReactDndWarning

Logs an error to the console if the enableDragAndDrop prop is true but the react-dnd and react-dnd-html5-backend dependencies are not loaded.