Custom hooks
You can also build your own hooks in React. Hooks' names should start with the use
- word, and they are JavaScript functions. Custom hooks can also call other hooks. With custom hooks, you can reduce your component code complexity.
Let's go through a simple example of creating a custom hook. We will create a useTitle
hook that can be used to update a document title. We will define it in its own file called useTitle.js
. First, we define a function, and it gets one argument named title
. The code is illustrated in the following snippet:
// useTitle.js function useTitle(title) { }
Next, we will use a useEffect
hook to update the document title each time the title
argument is changed, as follows:
import { useEffect } from 'react'; function useTitle(title) { useEffect(() => { document.title = title; }, [title]); } export default useTitle;
Now, we can start to use our custom hook. Let's...