React note #11

Yechan Jeon·2021년 12월 27일
0

React dev

목록 보기
11/18
post-thumbnail

Building custom hooks


What is custom hooks , why we use

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.

Define custom hooks

First of all, you should start function name with 'use' so that you can notice whether rule of hooks applied or not.

  • Example of custom hook
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) => {
  .
  .
};
profile
방황했습니다. 다시 웹 개발 하려고요!

0개의 댓글