UNPKG

@primer/react

Version:

An implementation of GitHub's Primer Design System using React

46 lines (42 loc) 1.66 kB
'use strict'; var reactCompilerRuntime = require('react-compiler-runtime'); var React = require('react'); /** * There are some situations where we want to give users the option to control state externally with their own state handlers * or default to using internal state handlers. Because of the 'rules-of-hooks', we cannot conditionally make a call to `React.useState` * only in the situations where the state is not provided as a prop. * This hook aims to encapsulate that logic, so the consumer doesn't need to be concerned with violating `rules-of-hooks`. * @param externalState The state to use - if undefined, will use the state from a call to React.useState * @param setExternalState The setState to use - if undefined, will use the setState from a call to React.useState * @param defaultState The defaultState to use, if using internal state. */ function useProvidedStateOrCreate(externalState, setExternalState, defaultState) { const $ = reactCompilerRuntime.c(5); const [internalState, setInternalState] = React.useState(defaultState); const state = externalState !== null && externalState !== void 0 ? externalState : internalState; let t0; if ($[0] !== setExternalState) { t0 = s => { setInternalState(s); if (setExternalState) { setExternalState(s); } }; $[0] = setExternalState; $[1] = t0; } else { t0 = $[1]; } const setState = t0; let t1; if ($[2] !== setState || $[3] !== state) { t1 = [state, setState]; $[2] = setState; $[3] = state; $[4] = t1; } else { t1 = $[4]; } return t1; } exports.useProvidedStateOrCreate = useProvidedStateOrCreate;