We derive the optimal portfolio for an expected utility maximizer whose utility does not only depend on terminal wealth but also on some random benchmark (state-dependent utility). We then apply this result to obtain the optimal portfolio of a loss-averse investor with a random reference point (extending a result of Berkelaar et al. (2004) Optimal portfolio choice under loss aversion, The Review of Economics and Statistics 86 (4), 973–987). Clearly, the optimal portfolio has some joint distribution with the benchmark and we show that it is the cheapest possible in having this distribution. This characterization result allows us to infer the state-dependent utility function that explains the demand for a given (joint) distribution.