{"record":{"id":"314e7f10fd53e71d","repo":"chakra-ui/chakra-ui","slug":"cannot-call-an-event-handler-while-rendering","errorCode":null,"errorMessage":"Cannot call an event handler while rendering.","messagePattern":"Cannot call an event handler while rendering\\.","errorType":"exception","errorClass":"Error","httpStatus":null,"severity":"error","filePath":"packages/react/src/hooks/use-callback-ref.ts","lineNumber":14,"sourceCode":"\"use client\"\n\nimport { useCallback, useInsertionEffect, useRef } from \"react\"\n\n/**\n * This hook is user-land implementation of the experimental `useEffectEvent` hook.\n * React docs: https://react.dev/learn/separating-events-from-effects#declaring-an-effect-event\n */\nexport function useCallbackRef<Args extends unknown[], Return>(\n  callback: ((...args: Args) => Return) | undefined,\n  deps: React.DependencyList = [],\n) {\n  const callbackRef = useRef<typeof callback>(() => {\n    throw new Error(\"Cannot call an event handler while rendering.\")\n  })\n\n  useInsertionEffect(() => {\n    callbackRef.current = callback\n  })\n\n  // eslint-disable-next-line react-hooks/exhaustive-deps\n  return useCallback((...args: Args) => callbackRef.current?.(...args), deps)\n}\n","sourceCodeStart":1,"sourceCodeEnd":24,"githubUrl":"https://github.com/chakra-ui/chakra-ui/blob/13692aee261402d0f4fd6eeab3a3857afcaae67b/packages/react/src/hooks/use-callback-ref.ts#L1-L24","documentation":"useCallbackRef is a user-land implementation of React's experimental useEffectEvent. The callback is stored in a ref whose initial value is a thunk that throws, ensuring the returned stable function is never invoked during the initial render pass (before useInsertionEffect has populated the ref). This enforces the React rule that effect-event callbacks may only fire from effects, event handlers, or callbacks — never synchronously while rendering.","triggerScenarios":"Calling the stable function returned by useCallbackRef during the first render — for example invoking it inline in JSX, inside useMemo, or directly in the component body before mount completes. Also triggered by tests or SSR that synchronously invoke the returned callback.","commonSituations":"Misusing the hook as a regular memoized callback that you can call during render; SSR/SSG where useInsertionEffect has not yet run; unit tests that synchronously call the returned function on a freshly mounted component.","solutions":["Only invoke the returned function inside event handlers, effects, timeouts, or other callbacks — never in the render body.","If you genuinely need the value during render, use useMemo/useCallback or read state directly instead of useCallbackRef.","In tests, wrap synchronous calls in act() and ensure effects flush before invoking.","Confirm you are not passing the callback into a child that calls it during its own render."],"exampleFix":"// before\nconst onClick = useCallbackRef(handler)\nreturn <div>{onClick('x')}</div> // throws on first render\n// after\nconst onClick = useCallbackRef(handler)\nreturn <div onClick={() => onClick('x')} />","handlingStrategy":"validation","validationCode":"// No pre-call validation possible — the error fires when the returned\n// callback is invoked during render. The guard is structural: never call\n// the returned function in the render phase.","typeGuard":"n/a (the contract is about *when* you call the returned function, not the input type)","tryCatchPattern":"try {\n  cb(...args)\n} catch (e) {\n  if (String(e) === 'Cannot call an event handler while rendering.') {\n    // move the call into an effect/handler instead of swallowing\n  }\n  throw e\n}","preventionTips":["Treat useCallbackRef's return value as an effect-event: call it only from effects, handlers, or callbacks.","Never invoke it in JSX, useMemo, useReducer initializer, or the component body.","In tests, flush effects (act()) before invoking.","On SSR, remember useInsertionEffect does not run server-side — do not invoke the callback during SSR."],"tags":["react-hooks","lifecycle","rendering","use-callback-ref"],"backgroundTag":null,"analyzedSha":"13692aee261402d0f4fd6eeab3a3857afcaae67b","analyzedAt":"2026-08-12T22:25:19.159Z","schemaVersion":2},"datasetVersion":"2026-08-12T23:17:12.415Z"}