With custom hooks, you can extract component logic and reuse it as a function.
When we build app, There will be duplicated logic definitely. This is the right case of why we use custom hooks.
By the way, as of hooks rule, we can use hook only in direct component function or in custom hooks. So if we want to extract that duplicated logic and apply it simultaneously, we need to build custom hooks.
First of all, you should start function name with 'use' so that you can notice whether rule of hooks applied or not.
const useCounter = () => {
const [counter, setCounter] = useState(0);
useEffect(() => {
const interval = setInterval(() => {
setCounter((prevCounter) => prevCounter + 1);
}, 1000);
return () => clearInterval(interval);
}, []);
return counter;
};
I created hooks directory and this code is in there.
Although you use useState or useEffect, the hooks will depend on where you apply this custom hooks.
As you can see, i returned 'counter' in useCounter hook. we can use this return object in where we use this custom hooks like useState, useReducer.
Again, The most important thing is naming of custom hooks (starts with 'use') and then return right value or object.
By the way, when most of logic is same, but a specific is different, you can set parameter in custom hooks.
const useCounter = (help) => {
.
.
};