Exercise 11 - React Hook - Useeffect - Usecontext
Exercise 11 - React Hook - Useeffect - Usecontext
Using the React Hook such as: Context & Effect Hook in your app.
const themes = {
dark: {
backgroundColor: 'black',
color: 'white'
},
light: {
backgroundColor: 'white',
color: 'black'
}
}
const initialState = {
dark: false,
theme: themes.light,
toggle: () => {}
}
Create a method which wraps all children with ThemeContext.Provider component and export this
method and the actual ThemeContext object that we created just before.
1
const isDark = !dark
localStorage.setItem('dark', JSON.stringify(isDark))
setDark(isDark)
}
const theme = dark ? themes.dark : themes.light
return (
<ThemeContext.Provider value={{ theme, dark, toggle }}>
{children}
</ThemeContext.Provider>
)
}
export { ThemeProvider, ThemeContext }
2
setDark(isDark)
}
const theme = dark ? themes.dark : themes.light
return (
<ThemeContext.Provider value={{ theme, dark, toggle }}>
{children}
</ThemeContext.Provider>
)
}
export { ThemeProvider, ThemeContext }
…
import { ThemeProvider } from './components/ThemeContext';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<ThemeProvider>
<App />
</ThemeProvider>
</React.StrictMode>
);
Update the Navigation.js component to perform the switch theme function as follow:
3
</a>
</div>
</nav>
</div>
)
}
Conclusions
In this exercise you learnt how to use Effect & Context Hook in your app.