ComposeHooks
ComposeHooks copied to clipboard
use React style hooks in Jetpack Compose to easier management state
ComposeHooks
English | 简体中文
About
The idea for the project comes from alibaba/hooks, which is a very easy-to-use collection of React Hooks.
It encapsulates most common operations as custom hooks, and useRequest is the top priority. It is
designed to be very lightweight, highly configurable, and easy to use.
Therefore, based on this design idea, Hooks that can be used in the Compose project were created using similar API names.
The hooks that have been implemented so far are as follows:
Note: All use functions also have the signature of remember. If you prefer Compose’s naming method, just use rememberXxx!
| hook name | effect |
|---|---|
| useRequest | Manage network requests and implement: manual and automatic triggering; life cycle callbacks; refresh; mutate changes; cancel requests; polling; Ready; dependency refresh; debounce, throttle; error retry; |
| useBoolean | Hook to manage boolean state. |
useBackToFrontEffect & useFrontToBackEffect |
Execute effect when app goes to the background or come back to the foreground |
| useContext | just like react |
| useCreation | useCreation is the replacement for useRef. |
| useDebounce | A hook that deal with the debounced value. |
| useDebounceFn | A hook that deal with the debounced function. |
| useEffect | just like react |
| useEvent | Implement lightweight cross-component communication using the subscribe-publish pattern |
| useInterval | A hook that handles the setInterval timer function. |
| useKeyboard | A Hook that controls the display and hiding of the soft keyboard. |
| useLatest | A Hook that returns the latest value, effectively avoiding the closure problem. |
| useMount | A hook that executes a function after the component is mounted. |
| useNow | A hook that return now date, default format:yyyy-MM-dd HH:mm:ss |
| useNetwork | A hook for obtaining network connection status and type. |
| usePersistent | A lightweight persistence hook, you need to implement the persistence method yourself (memory persistence is used by default) |
| usePrevious | A Hook to return the previous state. |
| useReducer | just like react |
| useRef | just like react |
useSelector/useDispatch |
easier to management global state,just like use redux-react |
| useState | just like react |
| useThrottle | A hook that deal with the throttled value. |
| useThrottleFn | A hook that deal with the throttled function. |
| useToggle | A hook that toggle states. |
| useTimeout | A hook that handles the setTimeout timer function. |
| useTimestamp | A hook that return now timestamp as a reactive state. |
| useUndo | A Hook for handling undo and redo. |
| useUnmount | A hook that executes the function right before the component is unmounted. |
| useUpdate | A hook that returns a function which can be used to force the component to re-render. |
| useUpdateEffect | A hook alike useEffect but skips running the effect for the first time. |
| useVibrate | A hook that make using vibration feedback easy |
Add to dependencies
implementation 'xyz.junerver.compose:hooks:<latest_release>'
implementation("xyz.junerver.compose:hooks:<latest_release>")
Quick Setup
-
Use
useStateto quickly create controlled componentsval (name, setName) = useState("") OutlinedTextField( value = name, onValueChange = setName, label = { Text("Input Name") } ) -
Use
useEffectto perform component LaunchedEffects -
Use
useRefto create object references that are not affected by component recomposeval countRef = useRef(0) Button(onClick = { countRef.current += 1 println(countRef) }) { Text(text = "Ref= ${countRef.current}") } -
Use
useRequestto easily manage network query stateval (data, loading, error, run) = useRequest( requestFn = WebService::login.asRequestFn(), //Encapsulate the corresponding extension functions yourself,to make retrofit friendly optionsOf { manual = true } ) if (loading) { Text(text = "loading ....") } if (data != null) { Text(text = "resp: $data") } if (error != null) { Text(text = "error: $error") } Button(onClick = { run(arrayOf(requestBody)) }) { Text(text = "Login") }useRequest organizes code through a plug-in pattern, the core code is extremely simple, and can be easily extended for more advanced features. Current features include:
- Automatic/manual request
- Polling
- Debounce
- Throttle
- Error retry
- Loading delay
- SWR(stale-while-revalidate)
- Caching
Live Templates
Copy hooks in the Live Templates directory
File, paste into C:\Users\<user-name>\AppData\Roaming\Google\AndroidStudio2023.2\templates\
You can easily create code snippets of useState and useRequest through us and ur.
Open Inlay Hints for Kotlin Type
For hooks like useRequest, its return value can deconstruct many objects and functions. It is necessary to enable InlayHint:
Editor - Inlay Hints - Types - Kotlin
Documentation
- Easily manage network requests with useRequest
- Using state hoisting in Compose? I'll hoisting to Provider
- How does a parent component call the function of a child component in Compose?
- How to use MVI idea conveniently in Compose? Try useReducer!
- Easily manage global state in Compose like using redux
Todo:
- KMP friendly
- Unit Test
- CI
- Complete documentation