Your Very Own Hook, Part 2 - abukhalil-LTUC-ASAC/amman-401d4 GitHub Wiki

Why make your own though?

Ok, you do need to learn how to make one, before using another that was pre-made, all for your apps. Custom hooks became so reusable, that it is generally a waste of time to write a whole app with your own hooks, unless you reused them from past projects or other hooks from elsewhere.

Conceptual understanding

A common theme is the prefix before the function "use", because that is how react recognizes custom hooks. One of many uses of these hooks is to handle forms and data, instead of handling it on a micro level, use a hook and deal with the outgoing data instead. Almost every aspect of your interactivity in the app could be replaced by a hook or two, or a hundred. The point is, captain hook dominates the scene here.

[Even bigger library and conceptual understanding is available in this repo, even those used by Alibaba the Chinese Amazon.

Some other notes

  • userReducer(): Ok, this is a tough one and relates to redux, which is yet to be understood, basically, it replaces useState() for complex logic that also depends on sub-values of past and the present, and maybe the future. Dispatch is the keyword.
  • useMemo(): this function helps reducing costly function with the method of memoization, think of a heavy logic or calculation you have to run every time something fires occasionally during rendering, but not side effects and reactions, it belongs in useEffect.

First hook example

Our first hook was about fetching data, this hook would use incoming stream from the form and update request from useEffect calls, have its internal states updated and return a list of data to be rendered, it handles a get, put and maybe even delete in a general way without showing much in the main files, very useful if we decided to implement an admin panel to many different schema's if an app has one.

Ending with context

Do you have dreams/nightmare's of data traversal in a react tree? Hopefully, you do. Because data passing down and up through props and callbacks are not joke to be taken lightly. Context though, allows for data to be globally available instead.

Lets get started with The solution to all of the miseries:

1- start with a declaration const ThemeContext = React.createContext('light');

2- render the child tree wrapped with the theme.

 return (
      <ThemeContext.Provider value="dark">
        <Toolbar />
      </ThemeContext.Provider>
    );

3- using the value at any level is provided with static contextType = ThemeContext; and render the value:

  render() {
    return <Button theme={this.context} />;
  }
⚠️ **GitHub.com Fallback** ⚠️