A reducer in React

React interview exercise on Context & reducers, difficulty 2 of 3. Solve it in the editor beside a worked example; the tests run the moment you do.

Write cartReducer(state, action) for a cart of { id, name, price, qty } lines: "add" (a line; if the id is already there, add 1 to its qty), "remove" (by id), "setQty" (by id; a qty of 0 or less removes the line), "clear". Never mutate the state. Then Cart({ catalog }) lists the catalog as buttons that add, the lines as <li className="line"> reading "Name × qty", and <p className="total"> with the total price.

Each exercise pairs a worked example with a twin problem to solve in a real editor; the tests run the moment you do. Progress is saved in your browser, and in your account if you sign in.

More Context & reducers in React

All React exercises · Other languages and frameworks