Hooks present the future of development with ReactJs — that is for sure.
Other than the basic hooks provided by the library itself, you can also write your own little hook (or a big one)! Those kinds of hooks are named Custom hooks. Taken straight from the React docs — a custom Hook is a JavaScript function whose name starts with ”use” and that may call other Hooks.
In this little how-to, I will be showing how you can do just that! (…and with TypeScript too).
In this example, I’ll show you how to implement a simple counter custom hook. Internally, it uses React’s useState and returns it along with a couple of other functions inside an object. The returned object is written with shorthand property names syntax.
const useCount = () => {
const [count, setCount] = useState<number>(0);
const increment = () => setCount(count + 1);
const decrement = () => setCount(count - 1);
const increaseBy = (increaser: number) => setCount(count + increaser);
const decreaseBy = (decreaser: number) => setCount(count + decreaser);
return { count, increment, decrement, increaseBy, decreaseBy };
};
Now, this hook can be used anywhere within a function component. Here’s an example:
const { count, increment, decrement, increaseBy, decreaseBy } = useCount();
<div>
<div>{count}</div>
<button onClick={increment}>increment</button>
<button onClick={decrement}>decrement</button>
<button onClick={() => increaseBy(20)}>increase by 20</button>
<button onClick={() => decreaseBy(20)}>decrease by 20</button>
</div>
#react #react hooks #javascript