1
\$\begingroup\$

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(() => (
    !checkbox
      ? 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">
        <input
          type="checkbox"
          id="theme-checkbox"
          defaultChecked={checkbox}
          onChange={() => setCheckbox(!checkbox)}
        />
        <span className="slidebar"></span>
      </label>
      🌒
    </div>
  )
}

Thanks for your help

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$
  • 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.

\$\endgroup\$

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.