What are React Hooks?

  • Functions for hooking into React state and lifecycle features
  • There are some rules!
  • Call them only at the top level
  • ...or from React function components (or your custom Hooks)

See what I mean (examples):

Built-in Hook useEffect

useEffect(() => {
    const data = MockedApi.fetchData();
    data.then((res) => {
      res.forEach((e) => {
        if (e.name === friendName) {
          setIsPresent(true);
        }
      });
    });
  });

See what I mean (examples):

Custom Hook useFriendName

export default function useFriendName(friendName) {
  const [isPresent, setIsPresent] = useState(false);
  ...
  return isPresent;
}

Why are they good thing?

  • Reusing logic - reuse your custom Hooks everywhere
  • Giant components - avoid building huge, hard to maintain components
  • Confusing classes - stop worrying about 'this' keyword and scope bindings

How to use React Hooks?

Important thing to remember is that we can use, both built-in and custom, hooks multiple times in our components.
We just have to follow the rules of hooks.

Examples coming...

* Note: In the following examples we will see different components built with currently existing class components approach. In the end of the presentation I will jump to the real application and show you comparison between them and the same components implemented with React Hooks.
<Counter />

You clicked 0 times

<DataFetcher />
<Clock />
The time is: 00 : 00 : 00

Conclusion

React Hooks are not really new feature that popped out just now. They are another (better ❓) way of doing React components that need to have state and/or lifecycle methods. Actually, they use the same internal logic that is being used currently by the class components.

To use them or not. This is the question that the future will give the best answer of.

References