Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/ebazhanov/how-to-usecontext-hook-in-react

Example of how to use react useContext hook
https://github.com/ebazhanov/how-to-usecontext-hook-in-react

Last synced: 26 days ago
JSON representation

Example of how to use react useContext hook

Awesome Lists containing this project

README

        

Motivation: better understand concept of how we can use in react `useContext` hook [orignal info](https://reactjs.org/docs/hooks-reference.html#usecontext)

#### When to Use Context
> Context is designed to share data that can be considered “global” for a tree of React components, such as the current authenticated user, theme, or preferred language. For example, in the code below we manually thread through a “theme” prop in order to style the

## First - create the themes which you want to use
```javascript
export const themes = {
dark: {
color: 'white',
background: 'black',
},
light: {
color: 'black',
background: 'white'
}
}
```
## Second - add component `Layout.jsx` with `useContext` hook, which will return style of your selected theme
```javascript
const Layout = () => {
const theme = useContext(ThemeColorBackground)

return (


here you can easily change "theme" by using React hook


useContext(themes.dark)


)
};
```

## Third and last - add new layout theme to your main `App.js` with `.Provider` key and value e.g.`value={themes.dark}` or `value={themes.red}
```javascript
function App() {
return (



);
}
```

### Usage:
- `yarn start`
- ![demo](useContextGif.gif)