Skip to content

Instantly share code, notes, and snippets.

@zakariaboualaid
Last active June 18, 2020 14:49
Show Gist options
  • Save zakariaboualaid/d086355717631d673a8c6794cebeae57 to your computer and use it in GitHub Desktop.
Save zakariaboualaid/d086355717631d673a8c6794cebeae57 to your computer and use it in GitHub Desktop.
//=====================================================================
// 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'}}
})
@bardouni
Copy link

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

const [state, dispatch] = useReducer(appReducer, initialState)
const Value = React.useMemo(() => [state, dispatch], [state]);
    return (
        <Context.Provider value={Value}>
            { children }
        </Context.Provider>
    )

@zakariaboualaid
Copy link
Author

Good to know, thank you 👍

@bardouni
Copy link

bardouni commented Jun 18, 2020

Thank you 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment