- Custom hooks are functions that can use React hooks
- Custom hooks can be used to share logic between components. In other words to create reusable logic
- Custom hooks can be used to abstract away complex logic, which means that your components can be more readable and easier to maintain when the business logic is separated from the component
- Custom hooks must start with the word
use
- Custom hooks can only call other hooks
- Continue last exercise. Create a new branch 'custom-hooks' with git.
- Create
hooks
folder in thesrc
of your project. AddapiHooks.js
file to thehooks
folder. - The idea is to make hooks for each path in the APIs we are using: login, users, media, etc.
- Create a custom hook
useMedia
toApiHooks.js
and move the functionalities fromHome.jsx
that are used to fetch media from the APIs to the useMedia hook:// TODO: add necessary imports const useMedia = () => { // TODO: move mediaArray state here // TODO: move getMedia function here // TODO: move useEffect here return {mediaArray}; }; export {useMedia};
Home
component after refactoring:const Home = () => { const [selectedItem, setSelectedItem] = useState( null, ); const { mediaArray } = useMedia(); return ( <> <SingleView item={selectedItem} setSelectedItem={setSelectedItem} /> <table> <tbody> {mediaArray.map((mediaItem) => ( <MediaRow key={mediaItem.media_id} item={mediaItem} setSelectedItem={setSelectedItem} /> ))} </tbody> </table> </> ); };
- The app should work as before. Test it.
- Git add, commit and push the changes to your repository.
(If we have time, we can refactor the other functionalities to custom hooks as well. For example, useUser hook for the user functionalities: getUserByToken()
, postUser()
etc. )
- Run
npm build
ornpm run build
- Move build folder to your public_html
- Test your app:
http://users.metropolia.fi/~username/custom-hooks
- Modify README.md. Change the link in
Open [X](X) to view it in the browser.
to point to the above link. - git add, commit & push to remote repository
- Submit the link to correct branch of your repository to Oma