Last active
June 18, 2020 14:49
-
-
Save zakariaboualaid/d086355717631d673a8c6794cebeae57 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//===================================================================== | |
// store.js | |
const initialState = { | |
data: {} | |
} | |
import React, { createContext, useReducer } from 'react' | |
import appReducer from './reducers/appReducer.js' | |
const Store = ({ children }) => { | |
const [state, dispatch] = useReducer(appReducer, initialState) | |
return ( | |
<Context.Provider value={[state, dispatch]}> | |
{ children } | |
</Context.Provider> | |
) | |
} | |
export const Context = createContext(initialState) | |
export default Store | |
//===================================================================== | |
/// reducers/appReducer.js | |
const Reducer = (state, action) => { | |
switch(action.type) { | |
case 'SOME_ACTION': | |
return { | |
...state, | |
data: action.payload | |
}; | |
break; | |
default: | |
return state | |
} | |
} | |
export default Reducer | |
//===================================================================== | |
// index.js | |
import Store from './store' | |
ReactDOM.render( | |
<Store> | |
<App /> | |
</Store> | |
, document.getElementById('root') | |
); | |
//===================================================================== | |
// App.js (OR ANY OTHER NESTED CHILD COMPONENT) | |
import { useContext } from 'react' | |
import { Context } from './store' | |
let [state, dispatch] = useContext(Context) | |
// Get global state | |
console.log('global application state :' + state.data) | |
// Set global state | |
dispatch({ | |
type: 'SOME_ACTION', | |
payload: {users: {id: 1, name: 'something'}} | |
}) |
Good to know, thank you 👍
Thank you 👍
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Passing value this way
value={[state, dispatch]}
will cause react to always trait the value as a diffrent value because a new array is created in every render , you can pass the the dispatch to a diffrent Provider or use this instead