The Weirdest Pattern in React

  Рет қаралды 7,481

Cosden Solutions

Cosden Solutions

Ай бұрын

🚀 Project React → cosden.solutions/project-react
Join The Discord! → discord.cosden.solutions
VSCode Theme | Font → Material Theme Darker | Menlo, Monaco "monospace"
In this video we will talk about the weirdest pattern in React. This is something that is in the official React docs, but isn't talked about often. The pattern is about setting state during rendering. Which is really weird to be honest. I will show you how to do it, and more importantly why to do it.

Пікірлер: 51
@lucasmachado6447
@lucasmachado6447 Ай бұрын
I unknowingly used this pattern in a project after trying to useEffect, remembering the "You might not need an Effect" part of the React docs and coming up with a solution. I didn't now how it worked behind the curtains though... Very good explanation!
@bsw4245
@bsw4245 Ай бұрын
so good to know fellow dev come up with the same solution as me. this trick got me going with extracting parameters of an url once the component got mounted and the only thing different was the slug
@estebanmurcia8451
@estebanmurcia8451 Ай бұрын
Same, i actually just used it today lol
@grustnoelitso6446
@grustnoelitso6446 Ай бұрын
Probably in this case you should restructure your components, move this state up and pass selected items as props
@nbaua3454
@nbaua3454 Ай бұрын
Bro, I like this channel so much so, no matter what I watch your stuff ASAP..
@imam_robani
@imam_robani Ай бұрын
Cool. It would be better if the log was displayed, so that the differences in rendering are clearer
@samuelwilliams6171
@samuelwilliams6171 Ай бұрын
Great content 💯
@samisiddiqui5286
@samisiddiqui5286 Ай бұрын
An alternative approach could involve generating a unique key by hashing the items array and assigning it to a key within the parent component. Additionally, this process could be encapsulated further by creating a child component responsible for the hash calculation, thereby allowing the parent component to remain independent of dictating the child component's behavior.
@jsmunroe
@jsmunroe Ай бұрын
What about using useMemo which runs in line. Like calling useMemo to set the state and then returning nothing. I've dont this before when I needed something like useEffect but that runs in line. Note that I have commented the snot out of it and most of the time I wrap in a syntactically obvious custom hook. But it does seem to work exactly like useEffect just in line.
@MrREALball
@MrREALball Ай бұрын
In those very rare scenarious, where you actually need this, you are prolly better off using useLayoutEffect. But the pattern shown in the video is the best one (one minor thing that you SHOULD change if you are gonna use it is create previousItems as useRef, since theres no need for reactivity). useMemo is more expensive than useRef and one if statement😝
@fortunethedev
@fortunethedev Ай бұрын
can you also reset the selectedItems state by passing items into the `key` prop for this child component?
@lord_kh4n
@lord_kh4n Ай бұрын
I guess we can't, key expects a string and turning array into a string might not be reliable
@ricohumme4328
@ricohumme4328 Ай бұрын
@@lord_kh4n you code json stringify it has a key, use length on the array. There are more options to that issue than you might think
@yawn74
@yawn74 Ай бұрын
​@@lord_kh4n what forturethedev means is When you change the items why not ? The key doesn't need to derieve from the array, it requires another way to get the key via either from the library uuid or so.
@asandratrynyavojohanesa462
@asandratrynyavojohanesa462 27 күн бұрын
When I read the documentation with useLayoutEffect, it describes the exact same use case.
@sugo8920
@sugo8920 Ай бұрын
I wish this hand an actual example of the problem in action and then shows how the new code fixes
@asmet2701
@asmet2701 Ай бұрын
Hi I wanna add an e-commerce store app for my portfolio. I wonder which react stack is solid for it in 2024. Can someone suggest something? As a back I would prefer Firebase, also for styling scss+mui but need recommendations about state manager and other technologies and tools. Thanks!
@taranveerjohal175
@taranveerjohal175 Ай бұрын
You dont always have a string being passed as Props in Production, might be beneficial to use Memo here for the props coming in instead of if statements
@abundancekendickson243
@abundancekendickson243 Ай бұрын
From the example, can we use "useLayoutEffect" instead of "useEffect", i gueas the former runs before the render
@TokyoXtreme
@TokyoXtreme Ай бұрын
You wouldn't use either, since you're not syncing the components with an outside system - there are no side "effects" to synchronize.
@yassinesafraoui
@yassinesafraoui Ай бұрын
Hmmm can't react solve this by checking if useEffect has a Dispatch inside its dependency array and prioritizing that useEffect's code? Just a suggestion though could be dumb
@MrREALball
@MrREALball Ай бұрын
It can not, react doesn't have a compiler (yet), so for react function passed in in useEffect is just a function, like any other and it has no idea (nor should it know) what it does. Plus, it would make useEffect even harder to understand, since in one instance it would run before "render", and in another - after.
@yassinesafraoui
@yassinesafraoui Ай бұрын
@@MrREALball yeah I agree that it would make it more confusing. But I don't think this needs a compiler, it will literally loop through the dependencies and check if they correspond to one of the state setters of the given component and if so it will run the code of the effect before each render, even for the problem of references I don't think there can be a problem since we're comparing functions
@MrREALball
@MrREALball Ай бұрын
@@yassinesafraoui state setters dont need to be in the dependency array (nor should they), since the reference never changes
@ivan4486
@ivan4486 Ай бұрын
why can't I just do const [ selectedItems, setSelectedItems ] = useState(items)? I know it is considered a bad practice, but I never could find an explanation on why...
@ricohumme4328
@ricohumme4328 Ай бұрын
Because useState holds the initial value across renders. The first time the component renders this will work, but after that the value is kept
@Edgars82
@Edgars82 Ай бұрын
it's not bad practice, but items are all items but in selected items you want to store selected items. But i would create logic in parent to get selected items and pass down function as prop. Or could map items with additional variable checked or some other approach to not do this weird thing. Also how he's actually handling item selection? as selected items are always epmpty. And i doubt that it stops at render and then does check again and only then renders. it renders component anyway 2 times. When function gets to return it does what is in return and doesn't returns before return. actually i have already something for selecting items parent UserList const [checkedItems, setCheckedItems] = useState([]); const handleCheckboxChange = (id: number, isChecked: boolean) => { if (isChecked) { setCheckedItems([...checkedItems, id]); } else { setCheckedItems(checkedItems.filter((itemId) => itemId !== id)); } }; {filteredList.map((conversation) => ( ))} and then in UserListItem const handleCheckbox = (event: ChangeEvent) => { const { checked } = event.target; onChange(conversation.id, checked); };
@yawn74
@yawn74 Ай бұрын
I am not sure if my answer is correct but I wonder why not change the key of this component? When you change the key it rerenders this component?
@MrREALball
@MrREALball Ай бұрын
It would work, but keep in mind that any other state would also be reset (which might not be what you want)
@mooraid
@mooraid 14 күн бұрын
This is great for auth-gating a route
@ViaxCo
@ViaxCo Ай бұрын
Isn't doing an equality check on an object (array) always going to fail? The references are different.
@brennenrocks
@brennenrocks Ай бұрын
I had this exact same thought. I feel that we would also need a useMemo in the parent for the array being passed in
@MitkoNS87
@MitkoNS87 Ай бұрын
It is the same object in memory as we assign it to the same object, not to copy of it.
@MrREALball
@MrREALball Ай бұрын
Arrays, objects and functions in JS are compared by reference. And since you pass in the exact same reference to useState and setPreviousItems(), it would 100% work. The exact same thing would've been an issue with useEffect otherwise. It wouldn't have worked only if one did something like setPreviousItems([...items]), than a new reference would've been created. Tip: do a deep dive into js memory model (stack, heap, garbage collector), it would pay off a lot in the long run, a lot of things would just snap into place.
@superbulletChinese
@superbulletChinese 29 күн бұрын
Basically react dev doc content.
@rslgomes
@rslgomes Ай бұрын
one question: on your solution: if (prevItems !== items) setSelectedItems([]); setPrevItems(items); why do you need tosetPrevItems to items? I mean: when the prop items change, prevItems will have a different value and setSelectedItems will trigger, which will proc a new reRender... on reRender, wouldnt prevItems be already equal to items, as useState will look at the prop to set prevItems Initial value, as this is a rerender of the component? im not saying you're wrong or anything... Im just curious about this logic
@rslgomes
@rslgomes Ай бұрын
ohhh... it holds the return statement... I get it now... I forgot the flow
@mohamedsalimbensalem6118
@mohamedsalimbensalem6118 Ай бұрын
can you make authentication and authorisation in frontend please
@bsw4245
@bsw4245 Ай бұрын
it reminds me of tower of hanoi case
@imfad3d
@imfad3d Ай бұрын
This is crazy. 😬
@ivan4486
@ivan4486 Ай бұрын
I don't get it. In your code selectedItems is always an empty array...
@ricohumme4328
@ricohumme4328 Ай бұрын
on initial render, yes. But when state changes are happening across renders, the initial value is not reset.
@PraiseYeezus
@PraiseYeezus Ай бұрын
This isn't going to work. Checking if two arrays === each other is always going to return false as they're different objects. You'll run into an infinite loop with your code, since those state setters are going to run over and over.
@RealAce333
@RealAce333 Ай бұрын
this approch execute on every render dosent matter if the arrays are different or not array1 !== array2 always return true
@VKD007
@VKD007 29 күн бұрын
just use a ref to hold previous state, instead of another state
@lord_kh4n
@lord_kh4n Ай бұрын
Isn't this like getDerivedStateFromProps? seems alike
@Stefoux
@Stefoux Ай бұрын
First comment !😏 cosden and the best patterns
@Stefoux
@Stefoux Ай бұрын
OUHAHHAHAHHAHA
@cosdensolutions
@cosdensolutions Ай бұрын
Congrats!
@user-oj1bc7td8k
@user-oj1bc7td8k 22 күн бұрын
But is there any sense to compare arrays? This isn't primitives , so array will never be equal to other array
Single Responsibility Principle in React (Design Patterns)
16:50
Cosden Solutions
Рет қаралды 43 М.
Efficiently Render 100,000 Rows in React
16:41
Cosden Solutions
Рет қаралды 15 М.
Kitten has a slime in her diaper?! 🙀 #cat #kitten #cute
00:28
Conforto para a barriga de grávida 🤔💡
00:10
Polar em português
Рет қаралды 100 МЛН
Stupid man 👨😂
00:20
Nadir Show
Рет қаралды 30 МЛН
The problem with useEffect
11:37
Cosden Solutions
Рет қаралды 30 М.
Vercel Gave Up On Edge
17:50
Theo - t3․gg
Рет қаралды 96 М.
I never thought of using CSS animations like this before!
10:28
Kevin Powell
Рет қаралды 64 М.
You might not need useEffect() ...
21:45
Academind
Рет қаралды 141 М.
State Managers Are Making Your Code Worse In React
13:33
Web Dev Simplified
Рет қаралды 144 М.
Setup VSCode like a senior React developer
13:43
Cosden Solutions
Рет қаралды 44 М.
98% Cloud Cost Saved By Writing Our Own Database
21:45
ThePrimeTime
Рет қаралды 254 М.
Design patterns in React
14:37
Cosden Solutions
Рет қаралды 138 М.
Server Components in React (Simple Tutorial)
25:27
Cosden Solutions
Рет қаралды 11 М.
Infinite Pagination Component With React Query
14:58
Cosden Solutions
Рет қаралды 13 М.
Kitten has a slime in her diaper?! 🙀 #cat #kitten #cute
00:28