V
V
vertically-challenged2022-03-02 18:33:57
React
vertically-challenged, 2022-03-02 18:33:57

Why does the theme change only after the second click on the radio button?

To change the theme, I use the following code:

The function that handles the click on the radio button, which I pass to the button from the App component:

const onThemeToggleHandler = (theme, setTheme) => {
  setTheme(theme == 'theme-dark' ? 'theme-light' : 'theme-dark')
}


The state of the theme and useEffect, in which the class change also occurs in the App component:

const [theme, setTheme] = useState('theme-dark')

  useEffect(() => {
    document.querySelector('.App').classList.toggle(theme)
  }, [theme])


Link to the running project
Link to the repository on gitHub

Answer the question

In order to leave comments, you need to log in

2 answer(s)
0
0xD34F, 2022-03-02
@vertically-challenged

How is the theme switched? The old class is removed, the new one is added. Let's see what you are doing:

useEffect(() => {
  document.querySelector('.App').classList.toggle(theme)
}, [theme])

Switch the new class. Do not add, but switch. And the old one - do not touch at all. We fix:
useEffect(() => {
  const el = document.querySelector('.App');
  el.classList.add(theme);
  return () => el.classList.remove(theme);
}, [ theme ]);

A
Alexandroppolus, 2022-03-02
@Alexandroppolus

Why manually change the class? This is "anti-React". Keep the theme in context, tie the render of the App component to a value from the context, change that value on click - the correct conventional way. And your version is fragile and generally stupid.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question