React Hooks useEffect Tutorial

Поделиться
HTML-код
  • Опубликовано: 3 окт 2024
  • Learn how to use the useEffect hook in React.
    Code: github.com/ben...
    Links from video:
    numbersapi.com/...
    overreacted.io...
    • React Hooks Closure Pr...
    Playlist: • React Hooks Tutorial
    ----
    If you like cooking, checkout my side project: www.mysaffrona...
    ----
    Join the Discord: / discord
    ----
    Patreon: / benawad
    ----
    Follow Me Online Here:
    Twitch: / benawad
    GitHub: github.com/ben...
    LinkedIn: / benawad
    Instagram: / benawad97
    Twitter: / benawad
    #benawad
    TikTok: / benawad ​

    ----
    Follow me online: voidpet.com/be...
    #benawad
  • НаукаНаука

Комментарии • 170

  • @ablanchi
    @ablanchi 5 лет назад +111

    Wow, this practical react series is like the distillation of so many long-ass tutorials where they basically treat you like you know nothing about anything for 3 hours.
    Please make more, these are gold Ben!

    • @JonathanJumper
      @JonathanJumper 4 года назад +2

      best comment, best video (y) suscribed

    • @marcelnunez1658
      @marcelnunez1658 3 года назад

      Honestly I'd prefer it to be slower but it's good nontheless

  • @habibsspirit
    @habibsspirit 5 лет назад +136

    Jesus Christ, MAN! How is this even possible?!?!? In under 2 minutes I understood more than I ever did with hours of reading those sophisticated lexicons some people call Documentation.

  • @valiknows
    @valiknows 5 лет назад +125

    Always prefer this type of tutorials vs React Docs 😂. All the best Ben !

  • @yotaraonvideo
    @yotaraonvideo 4 года назад +5

    Well, I'm gonna parrot everyone else's comments by saying that now I understand useEffect and React Hooks much better. Good stuff, Ben! 👍🏻

  • @amanbhayani65
    @amanbhayani65 4 года назад

    so happy to have found videos like this that just cut the BS, and are just focused on quick concepts. Definitely subscribed.

  • @jamesfoley4426
    @jamesfoley4426 5 лет назад +4

    Ben I like when you explain the theory shown in the React Doc's with a simple example. A lot of time the language in the React docs makes me have to look up what they are talking about....thanks for the help

  • @darkpsypher8567
    @darkpsypher8567 5 лет назад +6

    Thank you so much for doing these types of videos. You've improved my understanding of useEffect by a ton!

  • @mostinho7
    @mostinho7 11 месяцев назад +1

    UseEffrct is called whenever react rerenders but can limit the number of times it’ll be invoked by providing dependency array and then it’ll only be called when one of the vars in array changes

  • @jerrylove1759
    @jerrylove1759 4 года назад

    I can't thank you enough. I've been using react for over a year now but had never gotten to understand the useEffect hook. After carefully watching this video, I perfectly understand how and when to use it. I've also been able to fix some bugs in my code

  • @RACAPE
    @RACAPE 3 года назад

    I just started to use hooks at my job on a new project and this is super useful. Now all makes sense.

  • @anthonygayflor6168
    @anthonygayflor6168 5 лет назад +3

    Thank you for this! I really dislike the videos that explain things as if I’m learning code for the first time. But I REALLY like your style or tutorials, keep it up

    • @HCforLife1
      @HCforLife1 3 года назад +1

      Why to dislike videos like that? Lol. Just don't watch and skip it. There are people on different lvls - why to downvote helpful content. Just get to the habit of liking what is useful for you lol

  • @thomasboittin9626
    @thomasboittin9626 3 года назад

    Thanks for the tuto :)
    Quick note to add my experience:
    When I did the mouseMove event listener, I noticed that when I displayed the console while I was in responsive mode, the event was only triggered when I clicked. Removing the responsive mode makes it work.
    Noobies issue but it took me a bit to understand what was happening so I figured that it might help someone else :)

  • @timmyfrank3
    @timmyfrank3 3 года назад

    Thank you. Way better than other tutorials or react docs. Life saver.

  • @katielamber0238
    @katielamber0238 4 года назад

    I am very happy I got the time to watch the whole video series of yours. You rock! Love what you do. Many thanks to you!

    • @bawad
      @bawad  4 года назад +1

      awesome :)

  • @frogger832
    @frogger832 4 года назад

    Omfg I searched high and low for a simple explanation and here it is. Thank you.

  • @timothyn4699
    @timothyn4699 4 года назад

    Concise yet also well detailed, best explanation ive heard on effects so far, thanks!
    Also +1 for the keyboard tip on how to quickly comment out highlighted code

  • @davidallen2343
    @davidallen2343 5 лет назад +2

    These are great videos. Looking forward to the next already. Love your channel.

  • @ehodges2004
    @ehodges2004 5 лет назад +2

    Great series, look forward to more!

  • @restuwahyusaputra7764
    @restuwahyusaputra7764 4 года назад

    Thanks Ben for this tutorial, very helpful for me

  • @vorname1485
    @vorname1485 5 лет назад +2

    16:56 I would recommend only add stuff when lint asks for it. In this case lint is okay without setState because setState from useState will NEVER change once emitted. So the captured setState value inside the closure will never be stale. IN fact the lint plugin has this check for known cases backed into its implementation.

    • @TechnoTube001
      @TechnoTube001 4 года назад

      I was thinking exactly same, that I believe setState itself never changes so does it makes sense to include it in []

  • @bulletsblastsandbeasts6896
    @bulletsblastsandbeasts6896 5 лет назад

    This is just great! Exactly what I was looking for. Thanks, Ben!

  • @dragonburger5676
    @dragonburger5676 4 года назад

    Nice work Ben. Very helpful and great explanations!

  • @highzenburger1829
    @highzenburger1829 4 года назад

    Great tutorial and great typing speed!

  • @AhmedBesbes
    @AhmedBesbes 3 года назад

    I'm totally hooked to this React Hooks series!

  • @sreekumarmenon
    @sreekumarmenon 4 года назад

    if you declare async function inside useEffect , you can still use async/await , like so -
    const MyComponent = props => {
    useEffect(() => {
    async function myFunction() {
    await fetch(url);
    }
    // Execute the created function directly
    myFunction();
    }, []);
    return Asyncly!;
    };

  • @sstawecki
    @sstawecki 4 года назад +1

    Thanks dude! great explanation

  • @DevlogBill
    @DevlogBill 2 года назад

    Hi Ben, how you doing? Your video is now the 3rd video for React and the reason being is because I am having a real tuff time learning the useEffect method. Please correct me if I am wrong but the useEffect is used to refresh the state and for API's? My issue is understanding what the useEffect is for and how to properly write it. From what it seems you need the useEffect to connect to an API to gather data and use the try catch method to report errors? This is what I did in another tutorial. Hopefully 3rd time is the charm. I guess this time around if I don't understand it, I will simply repeat the process with this video over and over again until I finally understand what I am doing. Haven't seen the video yet but I am doing so now, and I would greatly appreciate any feedback, thank you.

  • @ryunosukeakutagawa6403
    @ryunosukeakutagawa6403 4 года назад

    It's very useful to understand useEffect than react website text tutorial.

  • @xerxius5446
    @xerxius5446 4 года назад

    Note that you don't need to add setState in dependency array because it is a stable function and it does not change its identity across renders and this is why ESlint will not complain about it either

  • @LautaroGruss
    @LautaroGruss 4 года назад

    Nice Ben, keep it up! Thanks for the videos!

  • @joerivde
    @joerivde 4 года назад

    Godlike explanation, thanks man!

  • @CodingwithElias
    @CodingwithElias 4 года назад +1

    good job!

  • @nathanbrachotte
    @nathanbrachotte 5 лет назад +6

    16:56 I don't think I understand why you're adding setState to the dependencies array.. Is the value of setState ever changing?
    Otherwise great video thanks a lot!

    • @bawad
      @bawad  5 лет назад

      the value of setState shouldn't change but if it were to change, we want the latest value so we add it as a dep

    • @jimioni9982
      @jimioni9982 5 лет назад

      @@bawad but setState is a function, how come it has a value? Unless you mean anytime setState is called/invoked. Please shed more light

    • @bawad
      @bawad  5 лет назад +2

      The value of a variable can change even if it stores a function:
      let add = (a, b) => a + b
      // I change the value here
      add = a => a

    • @timtomgouda
      @timtomgouda 4 года назад +2

      ​@@bawad I understand a function's definition can change in case of custom functions, but in this case will setState's definition change, since it is provided by React ?

    • @TechnoTube001
      @TechnoTube001 4 года назад

      @@timtomgouda Yes, you are right. setState definition will not change. I created this sandbox to test this: codesandbox.io/s/naughty-breeze-5kzky
      (I am not so sure if this is valid test, may be you or someone can check/verify it). I hope Ben answer this.

  • @kavinduchamiran4869
    @kavinduchamiran4869 3 года назад

    3:59 You can set chrome devtools' *preserve logs* to true to keep the logs even when the tab is reloaded.

  • @riongull
    @riongull 5 лет назад

    At 0:55 the word you’re looking for is “render fewer times” rather than “render less”.
    Thanks for your great material!

  • @moayedmustafa9673
    @moayedmustafa9673 4 года назад

    I get a weird feeling when I see Ben code? how does your brain work so fast and in unison with your fingers! I have a long way to go!

  • @JaeTask
    @JaeTask 5 лет назад

    very clear, thanks ben

  • @eric7758
    @eric7758 4 года назад

    Thanks ben.... this video saved me a bunch. hehehehehehehe. I'm so happy.

  • @StephenRayner
    @StephenRayner 5 лет назад

    An iffy is a good structure to use for the asynchronous useEffect. Can even make that its own hook. UseAsyncEffect

  • @shakibahmedshaikh7152
    @shakibahmedshaikh7152 4 года назад

    Hey, I thank you for this. I understood it better.

  • @consoledoterror971
    @consoledoterror971 4 года назад

    Huge Thanks for sharing this.

  • @mauricepheyton1386
    @mauricepheyton1386 4 года назад

    Great explanation!

  • @MDM666666
    @MDM666666 4 года назад

    Great tutorial, concise and straight to the point. Keyboard sounds amazing by the way, which board is it?

    • @bawad
      @bawad  4 года назад

      Thanks benawad.com/keyboard

    • @Septem_150
      @Septem_150 4 года назад

      Ben Awad 104-key gang rise up

  • @ibrahimalshubaily9520
    @ibrahimalshubaily9520 Год назад

    pretty pretty good (with Larry David voice)

  • @0the0ambient0
    @0the0ambient0 4 года назад

    Nice explanation. Thanks!

  • @uusa35
    @uusa35 4 года назад

    thank you amazing i really appreciate sharing your knowledge

  • @bjul
    @bjul 3 года назад

    Goddamit Ben, you are da bomb 🔥 God bless ya soul.

  • @АртурМорош
    @АртурМорош 4 года назад +1

    Watch you from Ukraine. Thanks you

  • @irvinghenriquez8231
    @irvinghenriquez8231 3 года назад

    wow great video. subscribed!

  • @kareemsakr41
    @kareemsakr41 5 лет назад

    Great work, thank you.

  • @worldclasscode1847
    @worldclasscode1847 2 года назад

    Great video! :)

  • @mohamedamarfilali
    @mohamedamarfilali 5 лет назад

    Great video, thank you

  • @szliang3974
    @szliang3974 3 года назад

    the 'useFetch' is actually a 'React component', however every time App component re-render, the 'useFetch' component get re-rendered too(called), even though inside useFetch, the useEffect shadow comparing [url], should useFetch wrapped into memo(useFetch)?
    another confusion is that:
    let us say the api response is delayed in few seconds, when App is doing rendering, the {data, loading} =useFetch(), have obtained the init value, which is null and true, is used in App rendering.
    few seconds later, not sure whether the App render the latest value? , i assume it works only like doing const state=useFetch(), in App return area use state.loading? 'loading': state.data

  • @keeganfargher6418
    @keeganfargher6418 4 года назад +2

    I always wrote it as {showHello ? : null} but your condition is so much cleaner

  • @bushigi5913
    @bushigi5913 4 года назад +3

    15:38
    even though we use (state=>({data:state.data, loading:true}))
    we still injected a new object(from the hooks point of view)
    how is this working?

    • @geekofia
      @geekofia 4 года назад

      he cleverly used data to show loading, infact that loading variable is not at all used. sate.data saving current state that is passed to hook ( null for first time and later old state of api response)

  • @TheYari1210
    @TheYari1210 4 года назад +1

    Wow! This guy is a bad ass! sub++

    • @bawad
      @bawad  4 года назад +1

      thanks and welcome :)

  • @succatash
    @succatash 3 года назад

    15:38 what exactly is the difference between setState({data:null, loading:false}) and setState(()=>({data:null, loading:false})) and what does making it a function do. does it just become a callback function, so if setState is rendered then we change the state of the object?

  • @MarcWilsonActual
    @MarcWilsonActual 4 года назад

    Great tutorial! A question regarding the functional component useFetch... It returns data, versus a react component (JSX). It's clearly ok, since it works, but I'm surprised about that. How is that a valid return value for a react stateless functional component?

  • @som.shekhar
    @som.shekhar 3 года назад

    At 15:47
    What's the point of having loading in the state, when we are almost never using it.
    { !data ? "loading..." : data}
    "loading..." only shows before the first data is fetched and then for subsequent fetches no "loading..."
    Is it intentional or by mistake?? Generally data fetching is not this fast so we would need loading before each fetch.

  • @denpol9956
    @denpol9956 4 года назад

    Good. But with debouncedCounterValue hook will be better )

  • @TheAmeer3881
    @TheAmeer3881 4 года назад +1

    Nice use of short-circuiting

  • @maksatbekburkanov4522
    @maksatbekburkanov4522 3 года назад

    What keyboard do you use Ben?

  • @geekofia
    @geekofia 4 года назад

    ​ @Ben Awad shouldn't we check localstorage value for null ? cause for the very first time we run, the number will be null ?

  • @errinwright
    @errinwright 2 года назад

    whoa Ben Damian Musk !1

  • @meaningmean
    @meaningmean 4 года назад

    Thanks so much ♥

  • @nischalsehrawat2130
    @nischalsehrawat2130 3 года назад

    Hi When does the useEffect hook of the usefetch run because there is no render method? i am a bit confused about the control flow here. Can you please explain a bit?

  • @fotoflo
    @fotoflo 4 года назад +1

    hi hi, wonderful tutorial here. Just one question - you use the initializer function of useState at 18:56 and you initialize it with a localstorage value.... how do you set the initial local storage value? let's say you wanted to start at 1 for example?

    • @bawad
      @bawad  4 года назад +2

      JSON.parse(localStorage.getItem('count')) ?? 1

    • @fotoflo
      @fotoflo 4 года назад

      @@bawad Thank you Ben!

    • @fotoflo
      @fotoflo 4 года назад

      @@bawad BTW why didn't you suggest using the || operator?

    • @fotoflo
      @fotoflo 4 года назад

      localStorage.getItem("null") ?? 1; // works in my code but returns an error in the chrome js console.
      localStorage.getItem("null") || 1 // returns 1 in the js console, also works in my code
      Uncaught SyntaxError: Unexpected token '?'

    • @bawad
      @bawad  4 года назад

      ?? needs babel plugin or typescript
      0 || 1 => 1
      0 ?? 1 => 0

  • @clydegrey5060
    @clydegrey5060 5 лет назад +1

    At 18:52 you say you don't want local storage to be called on every single render so you are initializing count with a callback function passed to useState. Even without doing this work in the passed function, it would still only access local storage one time (on the first render) and not on every render. Passing a function is not required to get the result you want. I agree that using the function will allow this fetching from local storage to happen asynchronously and is the better way of doing it. Am I mistaken?

    • @bawad
      @bawad  5 лет назад +1

      You're correct that it only sets the initial value once, but I think the code for JSON.parse and localstorage.getItem still run on each render

    • @clydegrey5060
      @clydegrey5060 5 лет назад +1

      @@bawad Oh I see it now. It gets evaluated at each render as it is an argument to useState, irrespective of the fact that useState only uses the value once (on mounting). Thanks! Great series.

    • @bawad
      @bawad  5 лет назад

      exactly

    • @AnilPai
      @AnilPai 4 года назад

      @@bawad I think you missed a return statement on Line 13.
      While fetching from localStorage always have a default value :-)
      return JSON.parse(localStorage.getItem("count")) || 0

    • @bawad
      @bawad  4 года назад +1

      return is only needed when you use curly braces

  • @kenhilliard5845
    @kenhilliard5845 5 лет назад +1

    When you call useFetch you destructure the returned object into const data = null and , const loading = true. Sometime later the fetch's promise completes. At this point useFetch updates "data" and "state" using setState. But how does this action update the App component's "data" and "loading" const values. They are const values, not references, so how does this happen? How does useFetch "reach up" and change the App's const values when the promise completes. It would seem to me the only way this could happen is if useFetch's setState call somehow causes the App component to re-render, resulting in a new call to useFetch which would return current state (data='retrieved data', state=false). Could you explain this. BTW: I really like your videos as they provide a much deeper insight into react along with best practices.

    • @bawad
      @bawad  5 лет назад

      "t would seem to me the only way this could happen is if useFetch's setState call somehow causes the App component to re-render, resulting in a new call to useFetch which would return current state (data='retrieved data', state=false)"
      that's right, when a hook calls setState the component it's in will rerender with the new state

  • @ahmad-ali14
    @ahmad-ali14 4 года назад

    awesome !!

  • @albinj20
    @albinj20 3 года назад

    why do we want to call localStorage.getItem inside a function ? It will be called on every first time render that's what we want right ?

  • @jamoliddinz
    @jamoliddinz 3 года назад

    thank youuuuu!

  • @ruirui7344
    @ruirui7344 3 года назад

    how to build hybrid (single + multi) page application using reactjs

  • @curlybrackets5049
    @curlybrackets5049 3 года назад

    great!!

  • @ChandanKumar-of1je
    @ChandanKumar-of1je Год назад

    which mechanical keyboard do you use???

  • @nodirbekvositov
    @nodirbekvositov 2 года назад

    Hello what happens if we remove cleaning up from this part 08:20

  • @abhinandankhilari9729
    @abhinandankhilari9729 4 года назад

    Could anyone explain why functions need to be passed in dependencies array? I got that on each render, the functions would get new references, but what would actually affect their behavior in such a way that effect needs to be run?
    Is it just a convention to specify functions as dependencies or would be there any actual scenarios when functions not passed in dependencies array leading logical errors?

  • @Sindoku
    @Sindoku 3 года назад

    Could you use the unmount for security purposes? Like, if you have some data that temporarily needs to be displayed and is sensitive, so if the user closes a modal it then triggers the unmount?

  • @zacktaylor1143
    @zacktaylor1143 2 года назад

    Is useForm a custom hook?

  • @chujunlu919
    @chujunlu919 2 года назад

    If anyone else experience the same issue? The first render of Hello, the console logs "render", "unmount", "render", instead of one single "render". That means the clean up function executes. I toggle button, console shows one "unmount" as expected. When I toggle again, three console logs: "render", "unmount", "render", where there should only be "render". I wonder why is this happening. Thank you!

    • @chrisstucker1813
      @chrisstucker1813 Год назад

      you must have react strict mode on. it makes useEffect() render twice, just turn it off

  • @kishorrathva4097
    @kishorrathva4097 4 года назад

    Why i am getting ""Warning: A component is changing a controlled input of type password to be uncontrolled". this warning initially ?

  • @logigunaratnam6870
    @logigunaratnam6870 4 года назад +1

    Hi, can someone explain why when you are setting the count in local storage, you use ```useState(() =>JSON.parse(localStorage.getItem("count")))``` instead of useState(JSON.parse(localStorage.getItem("count"))). When I tested both it didn't make a difference. Thanks in advance :)

    • @geekofia
      @geekofia 4 года назад

      that only gets count from local storage for the first time (once to be precise)

  • @Cmxmxmmx7
    @Cmxmxmmx7 4 года назад

    Hello,Ben! Thanks for tutorials. Recently I was trying to small game , where after user click button timer starts count down from 10 to 0. I am using hooks. I add clearInterval when seconds ===0, but infinite loop occurred. And one more questions. In one of your videos you suggested that react developers should learn PostgreSQL. What is the reason for that? Is mongoDb not enough?
    Thanks.

    • @bawad
      @bawad  4 года назад

      hard to say without looking at the code
      I think SQL is a more versatile skill, but I don't think it's bad to learn mongodb

  • @kevinhuang8733
    @kevinhuang8733 3 года назад

    What is useForm?

  • @DanishAnton
    @DanishAnton 4 года назад +1

    How come you have eslint validation without any eslint config file? Is it configured in vscode?

  • @gokubadgoku
    @gokubadgoku 5 лет назад +1

    DUUUUUUUUUUDE WE CAN MAKE SEARCH FILTERS USING THIS LOGIC I THINK IM NOT SURE BUT I THINK I HAD AN EPIPHANY

  • @lebroncode
    @lebroncode 4 года назад

    Why did you add setState to the dependency list in the useFetch hook?

    • @bawad
      @bawad  4 года назад

      Because it’s used inside

    • @lebroncode
      @lebroncode 4 года назад

      @@bawad But it doesn't matter if it changes right? Its just a function so it seems weird to me you would want to depend on that value

  • @asadsalehumar1011
    @asadsalehumar1011 5 лет назад

    At 10:59, I think the lint tells us to declare any async function inside the useEffect function, but not the useEffect function itself. What do you think?

    • @asadsalehumar1011
      @asadsalehumar1011 5 лет назад +6

      Whoops, next time I'll watch the next 5 seconds before putting comments

    • @bawad
      @bawad  5 лет назад

      😂👍

  • @krimo10
    @krimo10 4 года назад

    For some reason my component still renders twice even though I want it to render just once

  • @hellofriend3091
    @hellofriend3091 2 года назад

    Dope

  • @Anonymose43
    @Anonymose43 5 лет назад +1

    Hey Ben , i have one question please over using redux inside hooks, the problem is that my list in hooks component doesn't rerenders after i dispatch an action , but i see that the state in redux store is changed ???

    • @bawad
      @bawad  5 лет назад +1

      hard to say without looking at the code, could you put it in a codesandbox?

    • @Anonymose43
      @Anonymose43 5 лет назад

      @@bawad Here is my code : i paste just related file's codes it consist of 3 files (action, reducer and the hooks function's component) , here is the link on codepen :
      codepen.io/shadoo77/project/editor/AnqMKr

  • @alexfvcruz
    @alexfvcruz 4 года назад

    i like React but I'm not a fan of the way they do implement some stuff. Returning a function inside a function doesn't seem like a practical way to fire componentWillUnmout

  • @rajatsharma280
    @rajatsharma280 4 года назад

    Hey superb !!!
    I have a doubt if you could help me out in clearing this
    How to fetch get API which takes input parameter from form using axios using react hooks

    • @jandurcak8500
      @jandurcak8500 3 года назад

      const req = async () => {
      const { data } = await axios.get(url);
      // setquote({ data, loading: false });
      setquote({ quote: data, loading: false });
      };
      return req();

  • @princejoogie
    @princejoogie 3 года назад

    19:42 "useEffetch"

  • @MrNsaysHi
    @MrNsaysHi 4 года назад

    11:04
    ...OR! use an IIFE :3

  • @twiggeh3577
    @twiggeh3577 4 года назад

    amazing videos :)
    I tried using an async function with await in stead of the .then in the useFetch function. The result was a React boilerplate haha. Would you know the reason for it ? :)

    • @bawad
      @bawad  4 года назад

      What do you mean a react boilerplate?

    • @twiggeh3577
      @twiggeh3577 4 года назад

      @@bawad I'm not sure how to describe it, the first time I looked into react, the "installation" process of react created an "example page". For whatever reason I got that example page as html outputted into my data parameter :) (It was put out in a string format so I'm not entirely sure, but some parts were complaining about something not being a root ip ? )

    • @bawad
      @bawad  4 года назад

      hmm, I have no idea

  • @ClayMitchell
    @ClayMitchell 4 года назад

    If I wanted to add a button that would more information about the same number, is there a way to leverage the effect I already have, or do I need a new setState type function?

    • @bawad
      @bawad  4 года назад

      What do you mean?

    • @bawad
      @bawad  4 года назад

      What do you mean?

  • @EddieCheng174
    @EddieCheng174 4 года назад

    Can anyone told me how to do 2:07 thx?

  • @chubbyshady
    @chubbyshady 5 лет назад

    Can u make ur editor bigger? I watch on my phone and it's getting hard to read ur code

    • @bawad
      @bawad  5 лет назад +1

      yeah I'll trying zooming in one more level

  • @Eminence43rd
    @Eminence43rd 4 года назад

    You really enjoy typing.. I can tell..