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 - Наука
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!
best comment, best video (y) suscribed
Honestly I'd prefer it to be slower but it's good nontheless
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.
Documentation aka "THE HOLY SCROLLS!!!1!"
Literally my experience.
so true
Me Too
@@code_Jedi too
Always prefer this type of tutorials vs React Docs 😂. All the best Ben !
TRUEEEE LOL
React docs are fine.
Well, I'm gonna parrot everyone else's comments by saying that now I understand useEffect and React Hooks much better. Good stuff, Ben! 👍🏻
so happy to have found videos like this that just cut the BS, and are just focused on quick concepts. Definitely subscribed.
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
Thank you so much for doing these types of videos. You've improved my understanding of useEffect by a ton!
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
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
I just started to use hooks at my job on a new project and this is super useful. Now all makes sense.
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
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
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 :)
Thank you. Way better than other tutorials or react docs. Life saver.
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!
awesome :)
Omfg I searched high and low for a simple explanation and here it is. Thank you.
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
These are great videos. Looking forward to the next already. Love your channel.
Great series, look forward to more!
Thanks Ben for this tutorial, very helpful for me
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.
I was thinking exactly same, that I believe setState itself never changes so does it makes sense to include it in []
This is just great! Exactly what I was looking for. Thanks, Ben!
Nice work Ben. Very helpful and great explanations!
Great tutorial and great typing speed!
I'm totally hooked to this React Hooks series!
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!;
};
Thanks dude! great explanation
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.
It's very useful to understand useEffect than react website text tutorial.
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
Nice Ben, keep it up! Thanks for the videos!
Godlike explanation, thanks man!
good job!
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!
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
@@bawad but setState is a function, how come it has a value? Unless you mean anytime setState is called/invoked. Please shed more light
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
@@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 ?
@@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.
3:59 You can set chrome devtools' *preserve logs* to true to keep the logs even when the tab is reloaded.
At 0:55 the word you’re looking for is “render fewer times” rather than “render less”.
Thanks for your great material!
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!
very clear, thanks ben
Thanks ben.... this video saved me a bunch. hehehehehehehe. I'm so happy.
An iffy is a good structure to use for the asynchronous useEffect. Can even make that its own hook. UseAsyncEffect
Hey, I thank you for this. I understood it better.
Huge Thanks for sharing this.
Great explanation!
Great tutorial, concise and straight to the point. Keyboard sounds amazing by the way, which board is it?
Thanks benawad.com/keyboard
Ben Awad 104-key gang rise up
pretty pretty good (with Larry David voice)
Nice explanation. Thanks!
thank you amazing i really appreciate sharing your knowledge
Goddamit Ben, you are da bomb 🔥 God bless ya soul.
Watch you from Ukraine. Thanks you
wow great video. subscribed!
Great work, thank you.
Great video! :)
Great video, thank you
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
I always wrote it as {showHello ? : null} but your condition is so much cleaner
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?
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)
Wow! This guy is a bad ass! sub++
thanks and welcome :)
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?
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?
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.
Good. But with debouncedCounterValue hook will be better )
Nice use of short-circuiting
What keyboard do you use Ben?
@Ben Awad shouldn't we check localstorage value for null ? cause for the very first time we run, the number will be null ?
whoa Ben Damian Musk !1
Thanks so much ♥
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?
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?
JSON.parse(localStorage.getItem('count')) ?? 1
@@bawad Thank you Ben!
@@bawad BTW why didn't you suggest using the || operator?
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 '?'
?? needs babel plugin or typescript
0 || 1 => 1
0 ?? 1 => 0
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?
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
@@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.
exactly
@@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
return is only needed when you use curly braces
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.
"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
awesome !!
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 ?
thank youuuuu!
how to build hybrid (single + multi) page application using reactjs
great!!
which mechanical keyboard do you use???
Hello what happens if we remove cleaning up from this part 08:20
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?
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?
Is useForm a custom hook?
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!
you must have react strict mode on. it makes useEffect() render twice, just turn it off
Why i am getting ""Warning: A component is changing a controlled input of type password to be uncontrolled". this warning initially ?
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 :)
that only gets count from local storage for the first time (once to be precise)
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.
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
What is useForm?
How come you have eslint validation without any eslint config file? Is it configured in vscode?
Actually, I'm not sure
I think eslint validation comes already with create-react-app
DUUUUUUUUUUDE WE CAN MAKE SEARCH FILTERS USING THIS LOGIC I THINK IM NOT SURE BUT I THINK I HAD AN EPIPHANY
Why did you add setState to the dependency list in the useFetch hook?
Because it’s used inside
@@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
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?
Whoops, next time I'll watch the next 5 seconds before putting comments
😂👍
For some reason my component still renders twice even though I want it to render just once
Dope
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 ???
hard to say without looking at the code, could you put it in a codesandbox?
@@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
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
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
const req = async () => {
const { data } = await axios.get(url);
// setquote({ data, loading: false });
setquote({ quote: data, loading: false });
};
return req();
19:42 "useEffetch"
11:04
...OR! use an IIFE :3
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 ? :)
What do you mean a react boilerplate?
@@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 ? )
hmm, I have no idea
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?
What do you mean?
What do you mean?
Can anyone told me how to do 2:07 thx?
Can u make ur editor bigger? I watch on my phone and it's getting hard to read ur code
yeah I'll trying zooming in one more level
You really enjoy typing.. I can tell..