React Checkbox

Image of Author
August 2, 2022 (last updated September 21, 2022)

An odd thing about checkboxes in React is that you "control" the value via the checked attribute. But, the checked attribute is not particularly useful outside of React because it only represents the initial state of the checked components (see the note at the end of the value section for the input-checkbox docs).

The reason this is a viable approach in React is because every time the state of the checked prop changes, it updates the component containing the checkbox input. This causes the checkbox to rerender, which causes it to check (again) the checked attribute. This feels a bit like a hack because it is. You are circumventing the inherent state of the input that the browser controls, and instead controlling it within React itself. You are then forcibly rerendering this otherwise stateful element and forcing it to contain your React state on each render. I both feel bad about this on principal, and also continue to use React because controlling form state via Javascript is the most robust option.