Skip to content

Instantly share code, notes, and snippets.

View ohansemmanuel's full-sized avatar

Ohans Emmanuel ohansemmanuel

View GitHub Profile
const App = () => {
const [age, setAge] = useState(99)
const handleClick = () => setAge(age + 1)
const someValue = "someValue"
const doSomething = useCallback(() => {
return someValue
}, [someValue])
return (
<div>
const App = () => {
const [age, setAge] = useState(99)
const handleClick = () => setAge(age + 1)
const someValue = "someValue"
const doSomething = () => {
return someValue
}
return (
<div>
const initialState = { width: 15 };
const reducer = (state, newState) => ({
...state,
width: newState.width
})
const Bar = () => {
const [state, setState] = useReducer(reducer, initialState)
return <>
const initializeState = () => ({
width: 100
})
// ✅ note how the value returned from the fn above overrides initialState below:
const initialState = { width: 15 }
const reducer = (state, action) => {
switch (action) {
case 'plus':
return { width: state.width + 15 }
const initialState = { width: 15 };
const reducer = (state, action) => {
switch (action) {
case 'plus':
return { width: state.width + 15 }
case 'minus':
return { width: Math.max(state.width - 15, 2) }
default:
throw new Error("what's going on?" )
const ArrayDep = () => {
const [randomNumber, setRandomNumber] = useState(0)
const [effectLogs, setEffectLogs] = useState([])
useLayoutEffect(
() => {
setEffectLogs(prevEffectLogs => [...prevEffectLogs, 'effect fn has been invoked'])
},
[randomNumber]
)
// example Context object
const ThemeContext = React.createContext("dark");
// usage with context Consumer
function Button() {
return <ThemeContext.Consumer>
{theme => <button className={theme}> Amazing button </button>}
</ThemeContext.Consumer>
}
const ThemeContext = React.createContext('light');
const Display = () => {
const theme = useContext(ThemeContext);
return <div
style={{
background: theme === 'dark' ? 'black' : 'papayawhip',
color: theme === 'dark' ? 'white' : 'palevioletred',
width: '100%',
minHeight: '200px'
const ArrayDepMount = () => {
const [randomNumber, setRandomNumber] = useState(0)
const [effectLogs, setEffectLogs] = useState([])
useEffect(
() => {
setEffectLogs(prevEffectLogs => [...prevEffectLogs, 'effect fn has been invoked'])
},
[]
)
const ArrayDep = () => {
const [randomNumber, setRandomNumber] = useState(0)
const [effectLogs, setEffectLogs] = useState([])
useEffect(
() => {
setEffectLogs(prevEffectLogs => [...prevEffectLogs, 'effect fn has been invoked'])
},
[randomNumber]
)