|
| 1 | +--- |
| 2 | +templateKey: post |
| 3 | +title: useToggle |
| 4 | +date: "2020-12-02" |
| 5 | +gist: |
| 6 | +sandbox: |
| 7 | +isMultilingual: true |
| 8 | +--- |
| 9 | + |
| 10 | +Basically, what this hook does is that, it takes a parameter with value true or false and toggles that value to opposite. |
| 11 | +It's useful when we want to take some action into it's opposite action, for example: show and hide modal, show more/show less text, open/close side menu. |
| 12 | + |
| 13 | + |
| 14 | +```jsx |
| 15 | +import { useCallback, useState } from 'react'; |
| 16 | + |
| 17 | + |
| 18 | +// Usage |
| 19 | +function App() { |
| 20 | + // Call the hook which returns, current value and the toggler function |
| 21 | + const [isTextChanged, setIsTextChanged] = useToggle(); |
| 22 | + |
| 23 | + return ( |
| 24 | + <button onClick={setIsTextChanged}>{isTextChanged ? 'Toggled' : 'Click to Toggle'}</button> |
| 25 | + ); |
| 26 | +} |
| 27 | + |
| 28 | +// Hook |
| 29 | +// Parameter is the boolean, with default "false" value |
| 30 | +const useToggle = (initialState = false) => { |
| 31 | + // Initialize the state |
| 32 | + const [state, setState] = useState(initialState); |
| 33 | + |
| 34 | + // Define and memorize toggler function in case we pass down the comopnent, |
| 35 | + // This function change the boolean value to it's opposite value |
| 36 | + const toggle = useCallback(() => setState(state => !state), []); |
| 37 | + |
| 38 | + return [state, toggle] |
| 39 | +} |
| 40 | +``` |
| 41 | + |
| 42 | +```typescript |
| 43 | +import { useCallback, useState } from 'react'; |
| 44 | + |
| 45 | + |
| 46 | +// Usage |
| 47 | +function App() { |
| 48 | + // Call the hook which returns, current value and the toggler function |
| 49 | + const [isTextChanged, setIsTextChanged] = useToggle(); |
| 50 | + |
| 51 | + return ( |
| 52 | + <button onClick={setIsTextChanged}>{isTextChanged ? 'Toggled' : 'Click to Toggle'}</button> |
| 53 | + ); |
| 54 | +} |
| 55 | + |
| 56 | +// Hook |
| 57 | +// Parameter is the boolean, with default "false" value |
| 58 | +const useToggle = (initialState: boolean = false): [boolean, any] => { |
| 59 | + // Initialize the state |
| 60 | + const [state, setState] = useState<boolean>(initialState); |
| 61 | + |
| 62 | + // Define and memorize toggler function in case we pass down the comopnent, |
| 63 | + // This function change the boolean value to it's opposite value |
| 64 | + const toggle = useCallback((): void => setState(state => !state), []); |
| 65 | + |
| 66 | + return [state, toggle] |
| 67 | +} |
| 68 | +``` |
0 commit comments