MamorukunBE
MamorukunBE

Reputation: 120

Why is my onClick fired on component rendering?

In the following code (extract of complete code), the button onClick of ContextHookInfo component is fired directly when I refresh the page, and I don't have a clue why. Anyone has got an idea please?

const UseContextTheme = {
    light: {
        name: 'light',
        style: {
            color: "#0f0",
            backgroundColor: "#fff"
        }
    },
    dark: {
        name: 'dark',
        style: {
            color: "#fff",
            backgroundColor: "#0f0"
        }
    }
}

const HookContext = React.createContext({ selectedTheme: UseContextTheme.light, themeSetter: () => {} });

function App() {
    const [useContextSelectedTheme, useContextThemeSetter] = useState(UseContextTheme.dark);
    return (
        <HookContext.Provider value={{ selectedTheme: useContextSelectedTheme, themeSetter: useContextThemeSetter}}>
            <ContextHookTest>
                <ContextHookInfo />
            </ContextHookTest>
        </HookContext.Provider>
    );
}

function ContextHookInfo() {
    const themeContext = React.useContext(HookContext);
    console.log("Theme:", themeContext);
    return (
        <div>
            <p style={themeContext.selectedTheme.style}>Hook theme color is {themeContext.selectedTheme.name}</p>
            <button onClick={themeContext.themeSetter()}>Change hook theme</button>
        </div>
    );
}

Upvotes: 0

Views: 35

Answers (1)

Dipan Sharma
Dipan Sharma

Reputation: 1133

Change the function onClick={themeContext.themeSetter()} to onClick={themeContext.themeSetter}

Upvotes: 1

Related Questions