and my deepest appologies for the questions spam (I really have troubles understanding React learning it alone). In my actual code, I have created a context, specified to be able to change:
const ThemeContext = React.createContext(["light", () => {}]);
In my app function, I create a hook (I still doesn't clearly understand why, see my very last bonus question) on it so I'll be able to access those data in child components:
const themeHook = React.useState("light");
return (<ThemeContext.Provider value={themeHook}>...</ThemeContext.Provider>);
The component where I use it, I had to encompass it in a function to be able to to pass the hook data though props:
function ThemeTogglerFunction() {
const [contextType, toggleTheme] = React.useContext(ThemeContext);
return <ThemeToggler context={contextType} toggler={toggleTheme} />;
}
And finally, my ThemeToggler component can use that theme data and even switch between the two values I specified, I'm happy:
class ThemeToggler extends React.Component {
constructor(props) {
super(props);
this.handleToggle = this.handleToggle.bind(this);
}
handleToggle() { this.props.toggler(this.props.context === "light" ? "dark" : "light"); }
render() { return (<span style={ownStyle} onClick={this.handleToggle}>Toggle actuel {this.props.context} theme</span>); }
}
But then, if I insert the props into local properties (which sounds more proper to me):
class ThemeTogglerLocal extends React.Component {
constructor(props) {
super(props);
this.gloablThemeContext = props.context;
this.gloablThemeToggler = props.toggler;
this.handleToggle = this.handleToggle.bind(this);
}
handleToggle() { this.gloablThemeToggler(this.gloablThemeContext === "light" ? "dark" : "light"); }
render() { return (<span style={ownStyle} onClick={this.handleToggle}>Toggle actuel {this.gloablThemeContext} theme</span>); }
}
even if the hook value is correctly changed one ("light" becomes"dark") in the global ThemeContext (I can see it as everything is rerendered with the correct color change), the said local properties is not changed (is stays on "light") and so the app stays in "dark" mode from there. I suppose that is because the property is initialised in the constructor and have no more link with the hook, is it correct ? Does it mean that when you "import" a hook into a component, you shouldn't save it into local properties ?
Furthermore (small bonus question) : I had to create a hook in my app function, and I don't understand why, as React.createContext() already creates something which looks like a hook. Why can't I pass it directly the Theme Context.Provider (<ThemeContext.Provider value={ThemeContext}> in place of <ThemeContext.Provider value={themeHook}>) ?
Thank you very much in advance, and sorry for the length of this post.