Hooks
useBoolean
Purpose
Managing "loading" state of a component is very common task in React projects. For every state in every component, you have to call the useState
hook, then create from 1 to 3 callbacks to change the state. See the example code:
function ExampleComponent() {
const [loading, setLoading] = React.useState<boolean>(false);
const handleToggleState = React.useCallback(() => {
setLoading(!loading);
}, [loading]);
// ...
}
useBoolean
is implemented to help you handle boolean state easily without writing callbacks.
Usage
import { useBoolean } from "react3l-common"
function useCustomHook() {
const [
// boolean value
boolValue,
// toggle state
toggle,
// set state to true
setTrue,
// set state to false
setFalse,
] = useBoolean(false)
}
Example
The isVisible
state of a modal
const [
isVisible,
toggleModal,
openModal,
closeModal,
] = useBoolean(false);
useEffectSubscription
Purpose
If you subscribe to an observable in React component lifecycle, you have to cleanup the subscription when component unmount.
useEffectSubscription
handle the job for you.
Usage
Using pure effect
import { Observable, Subscription } from "rxjs"
function getUsers(): Observable<User[]> {
return new Observable((subscriber) => {
subscriber.next([])
})
}
function useCustomHook() {
React.useEffect(() => {
const subscription: Subscription = getUsers().subscribe((users: User[]) => {
// Do something
})
return function cleanup() {
subscription.unsubscribe()
}
}, [])
}
Using useEffectSubscription
import { useEffectSubscription } from "react3l-common"
import { Observable, Subscription } from "rxjs"
function getUsers(): Observable<User[]> {
return new Observable((subscriber) => {
subscriber.next([])
})
}
function useCustomHook() {
useEffectSubscription(getUsers)
}
useTimeout
To create and manage timeouts
Similar to useInterval, if you need a component that has an timeout during its lifecycle. useTimeout
is created for you.
For example: Mark something expired after x
seconds
function ExampleComponent() {
const [expired, setExpired] = React.useState<boolean>(false);
useInterval(
() => {
setExpired(true);
},
10000,
);
}
You don't have to care about calling clearTimeout
useInterval
To create and manage intervals
Sometimes, you may need a component that has an interval loop during its lifecycle. useInterval
is created for you.
For example: increasing counter
function ExampleComponent() {
const [counter, dispatch] = React.useReducer<Reducer<number, 'increase' | 'decrease'>>(
counterReducer,
0,
() => 0,
);
useInterval(
() => {
dispatch('increase');
},
1000
);
}
You don't have to care about calling clearInterval