How to Fix React Ref Not Working in AI-Built Apps
React refs return null or don't attach to the expected DOM element. AI-generated code often misuses refs with functional components, conditional rendering, or server components.
Error messages you might see
TypeError: Cannot read properties of null (reading 'focus')Warning: Function components cannot be given refs. Did you mean to use React.forwardRef()?Why this happens in AI-generated code
Ref used on functional component without forwardRef
AI passes a ref to a custom component that doesn't forward it to a DOM element.
Accessing ref before mount
AI reads `ref.current` during render or in useEffect without checking if the element is mounted.
Ref on conditionally rendered element
The element the ref points to is unmounted due to conditional rendering, leaving ref.current as null.
How to fix it
Use forwardRef for custom components
Wrap functional components with `React.forwardRef((props, ref) => ...)` or use the `ref` prop directly in React 19+.
Check ref.current before accessing
Always guard ref access: `if (ref.current) { ref.current.focus(); }` to handle cases where the element isn't mounted.
Get professional help
Our code audit identifies this issue and provides a fix. Start at springcode.co/products for $19.
Related technologies
Can't fix it yourself?
Our code audit identifies this issue and dozens more. Get a prioritized fix list.
Security Scan
Black-box review of your public-facing app. No code access needed.
- OWASP Top 10 checks
- SSL/TLS analysis
- Security headers
- Expert review within 24h
Code Audit
In-depth review of your source code for security, quality, and best practices.
- Security vulnerabilities
- Code quality review
- Dependency audit
- AI pattern analysis
Complete Bundle
Both scans in one package with cross-referenced findings.
- Everything in both products
- Cross-referenced findings
- Unified action plan
100% credited toward any paid service. Start with an audit, then let us fix what we find.
Frequently asked questions
When should I use refs vs state?
Use refs for imperative DOM access (focus, scroll, measure). Use state for values that should trigger re-renders when changed.
Do I still need forwardRef in React 19?
React 19 supports passing refs as regular props, so forwardRef is no longer required for new code.
Related resources
Related Technologies
Still stuck? We can fix it for you.
Send us your repo. We'll diagnose the issue and give you a fixed quote within 24 hours.