Skip to content

Instantly share code, notes, and snippets.

@guillermo
Last active May 9, 2019 15:09
Show Gist options
  • Save guillermo/abb7f590fcb9ade291e627681c970da3 to your computer and use it in GitHub Desktop.
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
// 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