React Custom Hooks with Axios Async useEffect | React Tutorials for Beginners

แชร์
ฝัง
  • เผยแพร่เมื่อ 8 ก.ค. 2024
  • Web Dev Roadmap for Beginners (Free!): bit.ly/DaveGrayWebDevRoadmap
    Build React custom hooks with Axios in this React tutorial for beginners. We'll construct our own useFetch hook that applies Axios instead of the Fetch API. We'll also get started with a simple custom hook called useWindowSize.
    🚩 Subscribe ➜ bit.ly/3nGHmNn
    🚀 This lesson is part of a Learn React tutorial series playlist:
    • React Tutorials
    🔗 Project Source Code: github.com/gitdagray/react_cu...
    React Custom Hooks
    (00:00) Intro
    (00:05) Welcome
    (00:19) Quick Set Up
    (00:43) Rules of Hooks
    (01:45) React Custom Hooks are like recipes
    (02:41) Creating the useWindowSize custom hook
    (08:46) Reviewing the useWindowSize custom hook
    (09:25) Applying useWindowSize to the React App
    (15:01) Remember the useEffect clean up function
    (17:20) Creating the useAxiosFetch custom hook
    (25:34) Reviewing the useAxiosFetch custom hook
    (27:16) Applying useAxiosFetch to the React App
    (35:19) Final clean up
    🔗 Rules of Hooks:
    reactjs.org/docs/hooks-rules....
    🔗 Collections of Hooks:
    nikgraf.github.io/react-hooks/
    www.npmjs.com/package/react-use
    🔗 Axios:
    www.npmjs.com/package/axios
    🔗 React Router:
    reactrouter.com
    🔗 JSON-Server:
    www.npmjs.com/package/json-se...
    🔗 ES7 React JS Snippets Extension for VS Code:
    marketplace.visualstudio.com/...
    🔗 React Dev Tools Extension for Chrome:
    chrome.google.com/webstore/de...
    🔗 Styled Components: styled-components.com/
    📚 References:
    ReactJS Official site: reactjs.org/
    React Wikipedia: en.wikipedia.org/wiki/React_(...)
    React Jobs: www.ziprecruiter.com/candidat...
    ✅ Follow Me:
    Twitter: / yesdavidgray
    LinkedIn: / davidagray
    Blog: yesdavidgray.com
    Reddit: / daveoneleven
    Was this tutorial about React Custom Hooks helpful? If so, please share. Let me know your thoughts in the comments.
    #react #custom #hooks
  • วิทยาศาสตร์และเทคโนโลยี

ความคิดเห็น • 72

  • @DaveGrayTeachesCode
    @DaveGrayTeachesCode  2 ปีที่แล้ว +13

    Creating React custom hooks is much like creating utility functions for React that you can use in various projects in the future. Essentially, React custom hooks are recipes that you can share. In this tutorial, we will create two custom hooks in React and apply them to the ReactJS Blog we've been building in this portion of the Learn React tutorial series. If you are just starting out with React, I recommend going to the beginning of the Learn React playlist here: th-cam.com/play/PL0Zuz27SZ-6PrE9srvEn8nbhOOyxnWXfp.html

  • @kostiantynkarzhanov9216
    @kostiantynkarzhanov9216 11 หลายเดือนก่อน

    Hi Dave! Thank you for all your lessons. Awesome content. Best channel ever! 💛

  • @eleah2665
    @eleah2665 2 ปีที่แล้ว +2

    This simple little app is getting somewhat involved. Very nice. Thanks.

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  2 ปีที่แล้ว

      You're welcome! 🙏 We're almost to the finish line 🚀

  • @isaacnewtonaranas3770
    @isaacnewtonaranas3770 2 ปีที่แล้ว

    awesome tuts! latest as well! i was looking for latest videos to get learn react with axios and these tuts are in the list. some are 10-8 months ago but this is a month only. very latest. GREAT!!! THANKS VERY MUCH!

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  2 ปีที่แล้ว +1

      Glad you like them! And thank you for the note! 🚀

  • @JonBrookes
    @JonBrookes ปีที่แล้ว +1

    Hi Dave,
    thanks for posting this well crafted video revealing the use of custom hooks in react. The example of a window resize hook is very clear, practical and thus easy to understand. The axios one likewize is the same and builds from this so as to crystallize key concepts.
    I came accros your channel looking for a better insight of migrating react to use typescript, for which your other content is also excellent. A veritable gold mine of information and learning 😊.

  • @mohamedyoussef8835
    @mohamedyoussef8835 2 ปีที่แล้ว

    Thank you for covering topics no one else has explained

  • @anazi
    @anazi ปีที่แล้ว +1

    When I need to learn something. I start with typing (Dave Gray ..... and then I type whatever I want to learn.)

  • @josephuzuegbu7431
    @josephuzuegbu7431 10 หลายเดือนก่อน

    I really like the tutorial. It explain useHook very well. Thanks

  • @Pareshbpatel
    @Pareshbpatel 2 ปีที่แล้ว +4

    Beautifully presented tutorial on creating and using custom hooks in React. Thanks, Dave
    {2022-02-21}

  • @rafael7425
    @rafael7425 2 ปีที่แล้ว +1

    very nice!!

  • @Ameersoccerdev
    @Ameersoccerdev 2 ปีที่แล้ว +1

    Great toturial I like it very much

  • @VuNguyen-yq6gs
    @VuNguyen-yq6gs 2 ปีที่แล้ว

    That's great! Thank sir!

  • @GetnetGetachew
    @GetnetGetachew ปีที่แล้ว

    simply thanks!

  • @fkbey5756
    @fkbey5756 2 ปีที่แล้ว

    Great tutorial, thnx sir.

  • @aswinvignesh3985
    @aswinvignesh3985 11 หลายเดือนก่อน +1

    Couple of questions ⁉️
    1. UsewindowSize runs only once as we log and we only use load time useEffect ,
    but can you explain how this makes custom hook to constantly updated the size as we remove eventlistner at the end of 1st run itself !?
    2. Is cancel token in axios cancels any previous request that is made ? And we make sure by isMounted to make a new request ? Am i right on this ?
    And also
    Thank you so much on this wonderful content 💕

  • @sonamohialdin3376
    @sonamohialdin3376 2 ปีที่แล้ว

    Awesome tutorial

  • @ivanfrey6323
    @ivanfrey6323 2 ปีที่แล้ว +7

    Hey Dave, I was a bit confused on the clean up function and 'memory leak' thing you mentioned, I wasn't sure what you meant. I think another way it can be mentioned is that we need that cleanup function because of this: When we refresh our page the component mounts, useEffect runs, and the Window has the event listener attached to it. However, the clean up function is necessary because when we reload the page again and cause our component to unmount for a small amount of time, we want to remove the event listener from the window object so that we are not constantly adding the event listener to the same object. It's like a light switch I guess, we want it on and off, never just on on on, etc. Let me know if this is the right way to think of it.

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  2 ปีที่แล้ว +4

      Ivan, you are correct! In addition, React used to provide a "memory leak" warning, but it was often unnecessary, so with React 18, that warning has now been removed. You're thinking is right - we do not want multiple event listeners added so we need to remove a listener on every unmount.

    • @ivanfrey6323
      @ivanfrey6323 2 ปีที่แล้ว +1

      @@DaveGrayTeachesCode Appreciate you Dave, the content is amazing.

    • @anangyoga1381
      @anangyoga1381 ปีที่แล้ว

      @@ivanfrey6323 kinda confused but thanks to your explanation, now I'm good.

  • @jiweihe3413
    @jiweihe3413 ปีที่แล้ว

    Thanks for the helpful video! I want to use the fetch data custom hook inside a handleClick() function, since I want to pass a query parameter to the URL by clicking a search button instead of a fixed URL. It gave an error. It seems we can only put hooks at the top of components. Should I use something else for this scenario?

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  ปีที่แล้ว +3

      This answer goes beyond a beginners tutorial, but custom hooks can also return functions. Therefore, you can create a custom hook to use at the top of your component that returns the function you want to call. I hope that makes sense! 🚀

  • @TheLucidway
    @TheLucidway 2 ปีที่แล้ว +1

    David, another really good tutorial! I just had a question about the "isMounted" var in the clean-up function. If the clean-up function fires right before useEffect runs again, isn't isMounted still going to be true until then? It seems like the time span between the component unmounting and the component re-mounting that isMounted would still be true.
    I placed a console log for isMounted within the clean-up function. The log from the clean up function only prints out right before useEffect is used again and it's value is false, but was it true before then and changed to false before useEffect ran, or did it have it's value changed to false when the component unmounted? I'm just confused as to when the clean-up function actually runs and isMounted's value is changed.

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  2 ปีที่แล้ว +2

      Good and thoughtful question! Instead of typing out a huge explanation, this article shows pretty much what is going on: dev.to/pallymore/clean-up-async-requests-in-useeffect-hooks-90h It even shows the unmounted component error we are trying to avoid in there. Good stuff! 💯

    • @TheLucidway
      @TheLucidway 2 ปีที่แล้ว

      @@DaveGrayTeachesCode Sweet, thanks, David!

  • @arefobaid8336
    @arefobaid8336 ปีที่แล้ว +1

    thanks but i dont understand how it when our compunent is unmounted we remove the eventlistener how it still work and check the size when the size of window is changed througth we have removed the listener

  • @nadatarekhassangaafar7874
    @nadatarekhassangaafar7874 9 หลายเดือนก่อน +1

    why did you use dataUrl as a dependency for useEffect?

  • @nikolasfuruta6938
    @nikolasfuruta6938 ปีที่แล้ว

    Hi Dave, thanks for the lessons! I have a question about 'useAxiosFetch'...in the data state, I wrongly put an empty string as the default state and everything went wrong...I don't know why this happens, since the default state is overwritten after the featch.

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  ปีที่แล้ว +1

      Your components will load before your data. It takes a little bit to fetch the data. So if your component is expecting an array, it is best to start out with an empty array as the default state.

  • @martin_orue
    @martin_orue ปีที่แล้ว

    Hi, Dave!
    Just to make sure I understood correctly: in this specific case, it wouldn't actually be necessary to check if the component unmounts, right? Because Feed is being rendered within Home, and Home will never be removed from the DOM (since it's rendered by default on the path '/').
    However, obviously, as it is a reusable hook, it is useful to perform that check in case it is needed in the future.
    Does what I'm saying make sense?
    Anyway, thank you for sharing these tutorials, I find them extremely helpful.

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  ปีที่แล้ว +1

      You're welcome! And yes, what you have said makes sense and is correct.

  • @insteresting
    @insteresting 7 หลายเดือนก่อน +1

    Hi Dave. Very nice tutorial as always! I have one question. At 30:00, you setPosts(data) inside the useEffect and also place data in the dependency array. Why didn't that cause an infinite loop, as everytime you setPosts, the dependency array changes? Maybe I am missing some point and can't find out what it is.

    • @vikaschandrakurella
      @vikaschandrakurella 17 วันที่ผ่านมา

      *useEffect* only runs when _data_ changes. If _data_ is fetched once and does not change, *useEffect* will not run again. If _data_ changes, the effect runs to update the state. If the fetched _data_ is same as the current state, no re-render is triggered. So, *useEffect* does not run again, preventing an infinite loop.

  • @MeAsMeButMe
    @MeAsMeButMe ปีที่แล้ว

    Are you also able to return setData from the useAxiosFetch hook so don't have to use posts as a separate piece of state or use a useEffect to set it. And the useEffect to filter the posts, can you just use useMemo for that? Thanks

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  ปีที่แล้ว +1

      It has been too long for me to remember the details, but in general, yes you can make any of these changes once you understand the concept of how a hook works.

    • @MeAsMeButMe
      @MeAsMeButMe ปีที่แล้ว

      @Dave Gray OK, I'm grateful for your answer! 🙏🏽

  • @mohamedyoussef8835
    @mohamedyoussef8835 2 ปีที่แล้ว

    Awesome videos and explanations ++++++++++++++++++++

  • @hungnguyencanh5089
    @hungnguyencanh5089 ปีที่แล้ว +1

    Thank you for great content. But one question, why you use UseEffect to SetData in App.jsx after create custom hook? It's already in custom hook

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  ปีที่แล้ว +1

      You can refactor and bring in the data variable from the custom hook as posts. You will also need to bring in the setData function as setPosts to completely eliminate the useState hook there. I did not want to dive into those extras as this beginner tutorial focused on enough already - but yes, there is usually more than way to arrive at the same result.

    • @hungnguyencanh5089
      @hungnguyencanh5089 ปีที่แล้ว

      @@DaveGrayTeachesCode Thank you so much for your explanation 😊

  • @kiranrai5014
    @kiranrai5014 ปีที่แล้ว

    Hello Dave, I have stuck in one part. the post method was working fine before the editPost method, but when I created the editPost method and the custom hook for the device width, the post method is continuosly showing me internal error when I click the handleSubmit button. I have checked the code thoroughly but I can't find any mistake, can you help me on how to overcome the internal error problem.
    const response = await api.post('/posts',newPost)
    this is causing problem in the try block, but I can't see any problem in this line.

    • @kiranrai5014
      @kiranrai5014 ปีที่แล้ว

      I have deleted all the data from the data/db.json and restart the program and it's working fine, I don't know what was the problem but it is fine.

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  ปีที่แล้ว +1

      Glad you got it going!

  • @AdityaDey424
    @AdityaDey424 ปีที่แล้ว +1

    What does 'isMount' mean ? Please explain it a bit !!

    • @chrisstucker1813
      @chrisstucker1813 ปีที่แล้ว

      It’s hard to explain but useEffect is similar to componentDidMount(); so once the useEffect is triggered, you know the hook/component is mounted. If the user navigates away to a page where the axios fetch hook isn’t being used, it will unmount and run the cleanup function which sets isMounted to false. The clean up function inside useEffect will always run whenever the hook unmounts. Hope that makes a bit more sense

  • @t0rinox607
    @t0rinox607 ปีที่แล้ว

    I always get a network error (can't load the blog posts)

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  ปีที่แล้ว

      Did you start json-server?

    • @t0rinox607
      @t0rinox607 ปีที่แล้ว

      @@DaveGrayTeachesCode i guess I've missed that. Cloned the repo and the code was the final version; so I just hit npm start, Thanks for the reply.
      Your (free) content is awesome! Keep going :)