Skip to content

Instantly share code, notes, and snippets.

@brickpop
Last active July 1, 2021 09:19
Show Gist options
  • Save brickpop/477f56f597046dac8730ce2cdde92da6 to your computer and use it in GitHub Desktop.
Save brickpop/477f56f597046dac8730ce2cdde92da6 to your computer and use it in GitHub Desktop.
React Hooks quick examples
// THE CONTEXT REFERENCE
const MyCounterContext = createContext<{ counter: number, setCounter: (n: number) => void }>({ counter: 0, setCounter: () => { } })
// PROVIDES ITS STATE TO CHILDREN COMPONENTS
const MyParent = ({ children }) => {
const [counter, setCounter] = useState(0)
return <MyCounterContext.Provider value={{ counter, setCounter }}>
{children}
</MyCounterContext.Provider>
}
// CONSUMES VALUES FROM ITS PARENT(S)
const MyChildren = () => {
const { counter, setCounter } = useContext(MyCounterContext)
return <p onClick={() => setCounter(counter + 1)}>hola {counter}</p>
}
// MAIN COMPONENT
const IndexPage = () => {
return (
<div>
<MyParent>
<MyChildren />
<MyChildren />
<MyChildren />
<MyChildren />
<MyChildren />
<MyChildren />
<MyChildren />
<MyChildren />
<MyChildren />
</MyParent>
</div>
)
}
// Splitting data logic from UI components
// Composable hooks
const useMyComponents = () => {
const [inputText, setInputText] = useState<string>("")
const [strings, setStrings] = useState<string[]>([])
const [stringCount, setStringCount] = useState<number>(0)
const [clickCounter, setClickCounter] = useState<number>(0)
const textChanged = (txt: string) => setInputText(txt)
const onClick = () => {
setStrings([].concat(strings).concat(inputText))
setClickCounter(clickCounter + 1)
}
const cleanStrings = () => setStrings([])
useEffect(() => {
setStringCount(strings.length)
// API CALL
}, [strings.join(",")])
return {
strings,
stringCount,
clickCounter,
textChanged,
onClick,
cleanStrings
}
}
// Simple UI component consuming data
const MyComponent = (props: { children: ReactNode, name?: string }) => {
const { strings, stringCount, clickCounter, textChanged, cleanStrings, onClick } = useMyComponents()
return <div>
<input type="text" onChange={e => textChanged(e.target.value)} />
<Button onClick={onClick}>Next</Button>
<Button onClick={cleanStrings}>Clean</Button>
<p>Strings: {strings.join(", ")}</p>
<p>Strings count: {stringCount}</p>
<p>Click counter: {clickCounter}</p>
</div>
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment