Last active
May 9, 2019 15:09
-
-
Save guillermo/abb7f590fcb9ade291e627681c970da3 to your computer and use it in GitHub Desktop.
React Hooks and Context for user in Kalena.app http://blog.kalena.app/day-6
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
// 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) |
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
// 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> | |
) | |
} |
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
// 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