I've just created a theme handler with React.js. Could my Theme component be polished and improved a bit ?

function Theme() {
  const [checkbox, setCheckbox] = React.useState(
    JSON.parse(localStorage.getItem("configuration"))?.dark_theme ?? true

  React.useEffect(() => (
      ? document.body.setAttribute('data-theme', 'light')
      : document.body.removeAttribute('data-theme'),
    setToLocalStorage({ dark_theme: checkbox }, "configuration") //memorization
  ), [checkbox])

  return (
    <div className="theme">
      <label htmlFor="theme-checkbox">
          onChange={() => setCheckbox(!checkbox)}
        <span className="slidebar"></span>

Thanks for your help


1 Answer 1

  • Names! Calling a variable that represents whether the theme is dark mode or not checkbox is pretty confusing. Why am I setting a local storage value to checkbox? It took me a moment to unwind that.

  • The comma operator inside the useEffect seems odd to me, but maybe that's how it's being done these days. I'd probably just braces around the function body and use regular JS statements.

  • The line setToLocalStorage({ dark_theme: checkbox }, "configuration") will work fine for now, but as soon as you introduce more configurations it will (mysteriously) wipe out all the other ones every time this checkbox is changed.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.