Created
May 5, 2020 10:45
-
-
Save adarsh0d/d36ed398b481ee2ece33e919f695f107 to your computer and use it in GitHub Desktop.
useMemo
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
import React, {useState, useContext, useMemo, useReducer} from 'react'; | |
const TextContext = React.createContext() | |
const FontContext = React.createContext() | |
const App = () => { | |
const [state, dispatch] = useReducer((prevState, action) => { | |
switch (action.type) { | |
case 'UPDATE_FONT_FAMILY': | |
return { | |
...prevState, | |
fontFamily: action.payload, | |
}; | |
case 'UPDATE_FONT_SIZE': | |
return { | |
...prevState, | |
fontSize: action.payload, | |
}; | |
case 'UPDATE_TEXT': | |
return { | |
...prevState, | |
text: action.payload, | |
}; | |
}, { | |
fontSize: 14, | |
fontFamily: 'Ariel', | |
text: 'Sample' | |
} | |
const textContext = useMemo(() =>{ | |
text: state.text, | |
updateText: (val) => dispatch({type: "UPDATE_TEXT", payload: val}) | |
}, [state.text]) | |
const fontContext = useMemo(() => { | |
fontSize: state.fontSize, | |
updateFontSize: (val) => dispatch({type: "UPDATE_FONT_SIZE", payload: val}) | |
fontFamily: state.fontFamily, | |
updateFontFamily: (val) => dispatch({type: "UPDATE_FONT_FAMILY", payload: val}) | |
}, [state.fontSize, state.fontFamily]) | |
return ( | |
<TextContext.Provider value={textContext}> | |
<Child1></Child1> | |
</TextContext.Provider> | |
<FontContext.Provider value={fontContext} | |
<Child2></Child2> | |
<Context.Provider> | |
) | |
} | |
const Child1 = () => { | |
//Need only text | |
const {text, updateText} = useContext(TextContext); | |
return ( | |
<React.Fragment> | |
<input value={text} onChange={(val) => updateText(val)}/> | |
<Child3></Child3> | |
</React.Fragment> | |
) | |
} | |
const Child2 = () => { | |
//This will have font family | |
const {fontFamily, updateFontFamily} = useContext(FontContext); | |
return ( | |
<React.Fragment> | |
<input style=`font-family: ${fontFamily}` onChange={(val) => updateFontFamily(val)}/> | |
<Child3></Child3> | |
</React.Fragment> | |
) | |
} | |
const Child3 = () => { | |
//want to access the fontSize | |
const {fontSize, updateFontSize} = useContext(FontContext); | |
return ( | |
<input value={fontSize} onChange={(e) => updateFontSize(e.target.value)}></input> | |
) | |
} | |
export default App |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment