Skip to main content
Version: v3.6.0

@rooks/use-interval

setInterval hook for React.​


Build Status

Installation​

npm install --save @rooks/use-interval

Importing the hook​

import useInterval from "@rooks/use-interval"

Usage​

function reducer(state, action) {
switch (action.type) {
case "increment":
return { count: state.count + 1 };
default:
return state;
}
}

function Demo() {
const [value, dispatcher] = useReducer(reducer, { count: 0 });

function increment() {
dispatcher({
type: "increment"
});
}

const { start, stop } = useInterval(() => {
increment();
}, 1000);

return (
<>
<p>value is {value.count}</p>
<button onClick={start}>Start</button>
<button onClick={stop}>Stop</button>
</>
);
}
render(<Demo/>)

Arguments​

ArgumentTypeDescriptionDefault value
callbackfunctionFunction be invoked after each interval durationundefined
intervalDurationnumberDuration in milliseconds after which callback is invokedundefined
startImmediatebooleanShould the timer start immediately or nofalse

Returned Object​

Returned object attributesTypeDescription
startfunctionStart the interval
stopfunctionStop the interval
intervalIdintervalIdIntervalId of the interval