12 / 13

What is the purpose of the `dangerouslySetInnerHTML` attribute in React?

Difficulty: 5/10
XSS prevention, HTML injection, React rendering
  1. 1

    dangerouslySetInnerHTML is used to inject HTML content into a component.

  2. 2

    it's named dangerous because improper use can expose your application to cross-site scripting (XSS) attacks.

javascript
javascript

Scenario Questions

0-2 years experience

  1. 1You need to render a piece of HTML content coming from a CMS inside a React component. How would you use dangerouslySetInnerHTML to do that, and what steps would you take to ensure it’s safe?
  2. 2If you forget to wrap the HTML string in an object with __html when using dangerouslySetInnerHTML, what will happen at runtime?

2-5 years experience

  1. 1Your team added a new feature that displays user‑generated markdown converted to HTML using dangerouslySetInnerHTML, and you start seeing XSS bugs in production. Walk me through how you would debug and fix the issue.
  2. 2When integrating a third‑party widget that requires injecting a script tag via dangerouslySetInnerHTML, what trade‑offs do you consider, and how would you mitigate potential security or performance impacts?

5-8 years experience

  1. 1We have a large dashboard that renders dozens of rich text blocks using dangerouslySetInnerHTML. How would you design a reusable component that sanitizes input, minimizes re‑renders, and stays performant at scale?
  2. 2Explain how you would implement a Content Security Policy and a sanitization pipeline to safely use dangerouslySetInnerHTML across multiple micro‑frontends in a monorepo.

8+ years experience

  1. 1Our organization is migrating legacy pages that heavily rely on dangerouslySetInnerHTML to a new component library. What architectural strategy would you propose to phase out the usage while maintaining security guarantees?
  2. 2How would you set up a cross‑team governance model (lint rules, code reviews, automated tests) to ensure that any new use of dangerouslySetInnerHTML follows strict security standards across the entire product suite?

Follow-up Questions

  • How does using a sanitization library like DOMPurify compare to manual string checks?
  • What performance differences might you notice between rendering raw HTML and building JSX?
  • How would you write tests to verify that unsafe markup cannot reach the browser?
Share

Share via WhatsApp, X, Facebook, LinkedIn or copy link. Open Graph preview enabled.