They both grew up in Destiny Isles with Riku being chosen to succeed Terra with his KeyBlade. At the start of the first game, Sora, Riku and Kairi are building a raft to see what was beyond the sea. The night before it was to sail, the Isles were attacked by the Heartless with Riku willingly stepping into the darkness. Maleficent was able to find the boy and corrupt him with the help of "Ansem" (really Xeanort's Heartless). After finding Kairi without her heart, Riku does whatever he can to revive her.
This made him oppose Sora and reclaim the KeyBlade only to lose it when Sora's heart became stronger than his. Riku then allows "Ansem" to posses him until he realizes he was a pawn. At the end of the game after "Ansem" is defeated, Riku helps Sora and Mickey seal the Door to Darkness, trapping Riku inside and rely on "Ansem."
In the second game, Riku is purified of "Ansem" but being exposed to darkness for so long enabled Riku to tap into its power without being corrupted. After atoning for his crimes, Riku became much more pure hearted and is now more willing to help those in need. Riku, like Sora is love with Kairi, but he doesn't act upon it since Kairi has feelings for Sora.