# TypeError: Cannot read properties of null (reading 'focus'). This error is located at: in MyComponent (at App.js:15)

- **ID:** `react/usecontext-null-focus`
- **Domain:** react
- **Category:** runtime_error
- **Verification:** ai_generated
- **Fix Rate:** 88%

## Root Cause

A ref is attached to a component or element that is conditionally rendered, and code tries to call ref.current.focus() when the element is not mounted (ref.current is null).

## Version Compatibility

| Version | Status | Introduced | Deprecated |
|---------|--------|------------|------------|
| react@18.2.0 | active | — | — |
| react-dom@18.2.0 | active | — | — |

## Workarounds

1. **Check if ref.current is not null before calling focus: `if (ref.current) { ref.current.focus(); }`** (95% success)
   ```
   Check if ref.current is not null before calling focus: `if (ref.current) { ref.current.focus(); }`
   ```
2. **Use useEffect with a dependency on the condition that controls rendering: `useEffect(() => { if (isVisible && ref.current) { ref.current.focus(); } }, [isVisible]);`** (90% success)
   ```
   Use useEffect with a dependency on the condition that controls rendering: `useEffect(() => { if (isVisible && ref.current) { ref.current.focus(); } }, [isVisible]);`
   ```

## Dead Ends

- **Using optional chaining (ref.current?.focus()) without understanding why ref is null** — Silently fails when the element is not mounted; the focus action never happens, which may be a UX issue. (50% fail)
- **Moving the focus call to useEffect with no dependency array** — May run before the element is rendered if the component conditionally renders the element later. (60% fail)
- **Using a callback ref and trying to focus immediately** — Callback refs are called during render, but the DOM may not be fully attached yet. (45% fail)
