Why you probably do not need useEffect
VloĆŸit
- Äas pĆidĂĄn 25. 05. 2023
- đ T3 Stack Tutorial: 1017897100294.gumroad.com/l/j...
đ€ SaaS I'm Building: www.icongeneratorai.com/
đŹ Discord: / discord
đ Newsletter: newsletter.webdevcody.com/
đ GitHub: github.com/webdevcody
đș Twitch: / webdevcody
đ€ Website: webdevcody.com
đŠ Twitter: / webdevcody
Can we just recognize trial and error and learning from your mistakes? Respect.
The second version is what I would have done (mixed with the setState(prev => ...). The derived state is great for performances but a little bit harder to read for humans, so I think it depend on the complexity and the performances you need
It can be easy to forget, reactive state changing not only causes the the ui to update but causes the whole component to rerun. So any function or non reactive state reliant on reactive state will change.
When I am tasked with fixing a react bug, the first thing I do is check for a useEffect.
I would consider that state is typically used for rendering stuff. And what is concretely rendered here? Either the numpad or the message. So imo the only state this component should have is the message string. Neither an isError bool where you have to derive the message from nor the pressedNumbers which are not visually represented, but rerender the component unnecessarily on every button click. So all you need is a by default null or empty message string state that gets updated by the click handler with a success or fail message after the necessary conditions can be evaluated (pressedNumber.length === 4 etc.). With !!message you render the state string, otherwise you render the numpad. Simple.
This was a great lesson on why you needed to refactor your code. You saw the problem, you've implemented your way of dealing with it, using useEffect, and then you saw how to improve on it!
I say this is great because I'm dealing with legacy code, and the logic approaches more with not needing an useEffect, but rather a derived state that just changes inside it whenever something changes.
It's harder to wrap your head around first, but then it just looks not only cleaner, but helps when the app gets more features for example. Nice video Cody!
Thanks man glad you liked it
Nice! You updated this! Couple more suggestions, although I wouldnât go back and change anything, adding âidleâ to state makes more sense for initialization. When I think of verbs ending with â-ingâ I think of something happening currently, at which point youâd debounce before updating state back to âidleâ. Thatâs really it from me. Great video!
Lines 15-18 could also be converted to a ternary since theyâre pretty self explanatory
That thread on your previous video was very educational. Kudos to the person that started this discussion!
This is why I use a state manager like Zustand.
What's the benefit of using zustand?
@@tech3425 Zustand is basically a global store like redux but is much simpler to use, very little boilerplate for managing all your states. Though, in a simple example like this one which is just a single component I think zustand is overkill. State managers become really useful when you want to manage states across multiple components (Especially sibling components).
Zustand is definitely an overkill for something simple like this
@@enyelsequeira3619 certainly is not considering it is unopinionated and a store can be created in a single line.
@@yzz9833 Interesting, I haven't really used it personally I've only looked into it and have seen projects at work using it. So do you use it for all cases in place of useState or useReducer?
Lol when you said âyou should read this articleâ I chuckled and said âI bet Cody skimmed it at bestâ lol sure enough thatâs what you said right after hahahahaha love you babe! Youâre doing great
You know me so well lol
Link to the article in description pls
Thankyou for great explanation. Please bring more tutorials on how to prevent re rendering and slow issues?
I feel like useEffect just sounds super intuitive to use because of how we think of processes as humans. Semantically "do this as a side effect when X changes" just sounds more... "complete?". Its often times more bloated code (and sometimes leads to broken code) but for me the first thing that comes to mind when im writing code like this is: "how can i achieve X running when Y changes, kind of a "side effect of something happening", oh yeah react basically has a hook for this! "
was waiting for this after i read that comment haha
glad you made it a video and broke it down
I would only use the state to display the end result, not store the entered numbers in it. and I would store the entered numbers with useRef so there is no re-rendering for every input. and on the last input, check if the password was entered correctly and change the final state to pass or fail
Great but I think is too much rendering when you are using the last approach because whenever this component is rendered is always buggy with if-else statements
Moving to a handler instead of useEffect definitely the right call. Don't know if i would completely remove useState though
I zeroed in on that doc article as soon as it went live. I've been freeing myself from overreliance on useEffect ever since.
I get it, Not using useEffect is good but I would still use 3 different state variables instead of checking for state of one variable at multiple places
What if I was using redux or zustand and wanted to do in a component if something in my store changed?
"number: string". Badass.
Would this be a valid use of useEffect:
I wanted to extend this challenge and allow the user to type an answer using the keyboard. I believe react provides onKeyPress or something similar for key presses, but when using that it seems that the user must be focused on the specific element. I wanted to be able to listen for key presses even when youâre not focused on the element. So I ended up using useEffect and registering an event listener on the document itself which would call the set function that I got from useState. I also had to make sure to remove the eventlistener afterwards, otherwise there would be multiple listeners for a single key press. It worked fine but I wonder if there was a more elegant solution.
Your useEffect doesn't have any dependencies(which are the cause of most issues) and you're using it to register an event handler so it's a completely legit solution if you don't want to add an input with onKeyPress
It sounds correct. It sounds like you need to manually add an event listener which useEffect is needed there; thatâs syncing with an external system (dom events)
very useful refactoring
if you can handle the state of the password synchronously this way then what's the point of using useState at all in this example? since you are not dealing with data fetching or external sources. couldn't you just use a let for the pressedNumbers as well?
You need at least one state to rerender the component for displaying the success / fail message.
You need state to force react to update the view
It's cleaner, I'd ask JSDoc or just a comment above the `if` logic and the handleNumberClicked just to remember to myself and coworkers what those blocks are doing.
What the mic youâre using Sir ?
Mxl 990
How do you do this renaming thing at 6:00?
F2
A function called "useEffect" which performs 30 different tasks depending on the number of empty arrays you pass in to it is much, much, much easier to understand than component lifecycle methods that do the one thing they say they do and if you don't believe that then you are not a real Millennial engineer.
can you show your vscode font?
Itâs the default for mac
@@WebDevCody ty bro
Do a vid where you build out an app using js doc instead of typescript. See if it is better.
I doubt it would be better
Yh I had the wrong idea, it works better for library authors like what sveltekit is doing.
useEffect & useState live in almost every file I have. Sorry I cannot change it, I like it its easier for me. I just hope they just don't deprecate it.
âuseEffect, aka useFootGunâ - Fireship
What is the name of this person? pls tell me anybody!
1st Approach is definitely the worst approach for all the reasons you listed and implied in my points below.
2nd Approach is the most clear to the general programmer outside of the web dev bubble
3rd Approach is better if you have experience with Java/TypeScript and some of the concepts in the React framework.
I think useEffect its more readable way to that
Not a front guy but the "useEffect" approach looks clearner and is more logical since it separates the logic for adding a new number from that that checks for password validity.
Next episode: why you probably do not need React đ
useEffect abstract all the steps you refactored, the bad is how useEffect implemented
I thought useEffect means "when these changed, do this" but maybe I'm wrong.
such a silly spaghetti code
lol why is this so overengineered
just have an event handler, put the currently clicked number in the array and do the logic based on its length and correctness
always do the simplest thing that works
Real
I think you should sit down 10 minutes before starting to record and think about video and problem you're working on.
Clearly it's not helpful to see you fumbling around trying to come up with a good solution.
Letâs see you make some videos
I like being able to see someone work through a problem. I feel as though that's the entire point of Cody's videos, unscripted raw thoughts. Even if he did "Sit down for 10 minutes before recording" I guarantee he'd walk out with a different solution anyways. This is how programming goes 90% of the time.
This comment screams imposter syndrome.
Actually this is far more helpful. Instead of watching someone rapid fire through code while trying to figure out what's going through their head and how they came to certain conclusions, I now have an understanding of the thought process that goes into coming up with these solutions.
Thatâs not the style I go for in my videos. I show you real software engineering, which is indeed fumbling around until you figure it out
What about reading state directly. You wont need to have variable passcode state.
const finishedAttempt = pressedNumber.length === expectedPassword.length
const isPasswordCorrect = pressNumbers === password
....{finishedAttempt ?
{isPasswordCorrect ? Success! : "Bad password"}
: null}...
In this approach, my variable is always changing between re-renders. And even though it gets corrected again by the if statements, I prefer to make them as stable as possible to avoid my messy hands from introducing a mistake in the future. Therefore, I would still encapsulate everything, but in a reducer:
type InputState = "typing" | "success" | "error"
type ReducerState = { inputState: InputState; password: string }
...
const [state, dispatch] = useReducer(
(prevState: ReducerState, action: number): ReducerState => {
const updatedPassword = prevState.password + action
if (updatedPassword.length !== PASSWORD.length) {
return { inputState: "typing", password: updatedPassword }
}
if (updatedPassword === PASSWORD) {
return {
inputState: "success",
password: "",
}
}
return {
inputState: "error",
password: "",
}
},
{
password: "",
inputState: "typing",
}
)
...
onClick={() => dispatch(n)}
...
what you think of the following code. to reuse the state and what you think of it's computation and performance.
const [state, setState] = useState({
email_length: 'medium',
content_count: details?.selectedRows,
email_style: 'Casual',
sale_type: 'Product',
sale_message: '',
});
const updateState = (category, option) => {
setState((prevState) => {
return {
...prevState,
[category]: option,
};
});
};
onClick={() => updateState('email_style', 'Casual')}
I've done that before, seems fine imo