ianstormtaylor/slate · error · Error

The `useElement` hook must be used inside `renderElement`.

Error message

The `useElement` hook must be used inside `renderElement`.

What it means

useElement is a slate-react hook that returns the current Element via React context (ElementContext). That context is only provided by Slate's internal component that renders elements inside renderElement. Calling useElement outside a component that is rendered as part of renderElement means the context is undefined, so the hook throws to make the misuse obvious.

Source

Thrown at packages/slate-react/src/hooks/use-element.ts:14

import { createContext, useContext } from 'react'
import { Element } from 'slate'

export const ElementContext = createContext<Element | null>(null)

/**
 * Get the current element.
 */

export const useElement = (): Element => {
  const context = useContext(ElementContext)

  if (!context) {
    throw new Error(
      'The `useElement` hook must be used inside `renderElement`.'
    )
  }

  return context
}

/**
 * Get the current element, or return null if not inside `renderElement`.
 */
export const useElementIf = () => useContext(ElementContext)

View on GitHub (pinned to 72a37c701e)

Solutions

  1. Move the useElement() call into a component that is returned from your renderElement prop
  2. Use useSelected()/useSlate() only if you don't need the element, or pass the element down as a prop instead
  3. Double-check the component tree: useElement must be a descendant of the component Slate renders per element

Example fix

// before
const Leaf = props => {
  const el = useElement() // throws: leaf components have no ElementContext
  return <span {...props.attributes}>{props.children}</span>
}

// after
const Element = ({ attributes, children, element }) => {
  const el = useElement() // ok: inside renderElement
  return <p {...attributes}>{children}</p>
}
Defensive patterns

Strategy: type-guard

Type guard

const useElementOrNull = () => {
  const ctx = useContext(ElementContext)
  return ctx // undefined when outside renderElement
}

Prevention

When it happens

Trigger: Calling useElement() in a component rendered outside renderElement — e.g. inside renderLeaf, renderPlaceholder, a toolbar, or at the top level of your app; using it in a custom hook invoked from a non-Slate component.

Common situations: Copy-pasting a leaf component that also tries to read the element; refactoring element rendering so the component is no longer mounted via renderElement; using useElement in decorations rendering.

Related errors


AI-assisted analysis of ianstormtaylor/slate@72a37c701e (2026-08-27). Data as JSON: /api/errors/4ef757e71b61e21b. Report an issue: GitHub.