The Da Vinci Code hit the religious/occult conspiracy theory market, which was huge at the time, and added feminist overtones about the "divine feminine" which appealed to most female New Agers and a good few male ones.
His other books didn't have those ingredients, and they were less successful.
More recently we've had Fifty Shades and Romantasy. Working out the demographics and the reader appeal is left as an (easy) exercise for the reader.
Harry Potter and Young Adult classics like The Hunger Games are a little harder to analyse, but not much.
Someone like Stephen King is less obvious. (For most of the books "horror" is the hook, but American small town relatability is at least as important.)
Writing quality isn't quite incidental. But it only needs to be above a certain minimal level of competence, nowhere near what's usually called "good writing."
Books which have "good writing" but don't trigger a large demographic of readers with specific fears and/or fantasies - of any kind - do not do well.