React Hooks and Context for user in Kalena.app http://blog.kalena.app/day-6
// We create a context interface with a reducer | |
import React, {createContext, useContext, useReducer} from 'react' | |
export const UserContext = createContext(); | |
export const UserProvider = ({reducer, initialState, children}) =>( | |
<UserContext.Provider value={useReducer(reducer,initialState)}> | |
{children} | |
</UserContext.Provider> | |
) | |
// We create a shortcut to make it easy to call | |
export const useUserValue = () => useContext(UserContext) |
// Then we create the provider in the App so we have a context within all child components | |
import React from 'react' | |
import Stats from '../Stats'; | |
import {UserProvider} from '../../userContext' | |
export default () => { | |
const initialUserState = { | |
birthYear: 1983, | |
deathYear: 1983+86 | |
} | |
// We have an empty reducer so far | |
const reducer = (state,action) => { | |
return state | |
} | |
let [width,height] = useWindowSize() | |
return (<UserProvider initialState={initialUserState} reducer={reducer}> | |
<Stats/> | |
</UserProvider> | |
) | |
} |
// With two lines we access the context | |
import React from 'react' | |
import Box from '../Box' | |
import {useUserValue} from '../../userContext' | |
export default function Stats(props) { | |
const [user,dispatch] = useUserValue() | |
return <Box {...props} >= {JSON.stringify(user)} =</Box> | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment