Skip to content

Instantly share code, notes, and snippets.

@Patrick-DS
Last active October 31, 2020 21:37
Show Gist options
  • Save Patrick-DS/f63b23537f5a9230486f1503bce28bdd to your computer and use it in GitHub Desktop.
Save Patrick-DS/f63b23537f5a9230486f1503bce28bdd to your computer and use it in GitHub Desktop.
// useBoolean.js
import { useState, useCallback } from "react"
const useBoolean = (initialState) => {
const [booleanValue, setBooleanValue] = useState(initialState)
const setValueToTrue = useCallback(() => setBooleanValue(true), [setBooleanValue])
const setValueToFalse = useCallback(() => setBooleanValue(false), [setBooleanValue])
const toggleValue = useCallback(() => setBooleanValue(!booleanValue), [booleanValue, setBooleanValue])
return [booleanValue, setValueToTrue, setValueToFalse, toggleValue]
}
// ExampleComponent.js
import React from "react"
import { useBoolean } from "./hooks"
import { ComponentOne, ComponentTwo } from "./somewhere"
const ExampleComponent = (props) => {
const [isComponentOneShown, showComponentOne, hideComponentOne, toggleComponentOne] = useBoolean(false)
return (
<>
{isComponentOneShown && (
<ComponentOne {...props} onClick={hideComponentOne} onSomething={toggleComponentOne} />
)}
<ComponentTwo {...props} onClick={showComponentOne} />
</>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment