Skip to content

Instantly share code, notes, and snippets.

@adarsh0d
Created May 5, 2020 10:45
Show Gist options
  • Save adarsh0d/d36ed398b481ee2ece33e919f695f107 to your computer and use it in GitHub Desktop.
Save adarsh0d/d36ed398b481ee2ece33e919f695f107 to your computer and use it in GitHub Desktop.
useMemo
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