Home > Software engineering >  how can i save the dark mode state in react
how can i save the dark mode state in react

Time:03-08

I am wondering how I can save the state of dark mode in my components so I can use it without getting the initialized value over and over again when i navigate different pages. this is the code :

class Toggle extends React.Component {
    constructor(props) {
        super(props);
        this.state = { isDark: false }
        this.handleOnClick = this.handleOnClick.bind(this);
    }
    handleOnClick = () => {
        this.setState(prevState => ({ isDark: !prevState.isDark }))

    }
    componentDidUpdate() {
        if (this.state.isDark === true) {
            setTheme('theme-dark');
        } else setTheme('theme-light');
    }

CodePudding user response:

I would go take a look at React Context, themeing is a prime use case for it https://reactjs.org/docs/context.html#dynamic-context

  • Related