How to show error state in React

Handling and displaying error states properly is essential for building robust React applications that gracefully handle failures and provide clear feedback to users. As the creator of CoreUI, a widely used open-source UI library, I’ve implemented error handling in thousands of production components over 25 years of development. From my expertise, the most reliable approach is using useState to store error information and conditional rendering to display user-friendly error messages. This ensures users understand what went wrong and how they might resolve issues.

Use useState to store error state and conditionally render error messages.

const [error, setError] = useState(null)

return error ? <div className="error">{error}</div> : <div>Content</div>

Here the error state holds error messages or null when no errors exist. When an error occurs, set the error message with setError('Something went wrong'). The conditional rendering displays the error message when present, or normal content when error is null. Clear errors with setError(null) when retrying operations or navigating away.

Best Practice Note:

This is the same error handling pattern we use in CoreUI components for API calls and form validation. Always provide actionable error messages and consider adding retry mechanisms or fallback UI to help users recover from errors gracefully.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author