DEV Community

Discussion on: 10 ReactJS Coding Challenge (💥Coding Interview Prep💥)

Collapse
 
mkmckenzie profile image
Mary-Katherine McKenzie

Great exercises! Had fun with these!!

One thing I want to note - in your solutions, I often see the pattern:

const [value, setValue] = React.useState(0)

<button onClick={setValue(value +1)}>Increment</button>
Enter fullscreen mode Exit fullscreen mode

However, the React docs prefer this method of using the previous state value - passing a function that receives the previous state value.

const [value, setValue] = React.useState(0)

<button onClick={setValue(prevValue => prevValue + 1)>
    Increment
</button>
Enter fullscreen mode Exit fullscreen mode

Updating state with value instead of using the previous state function may result in some buggy behavior because of React's unpredictable & async state-updating logic. Likely won't see anything buggy with these examples since they aren't too complex, but just wanted to shout out that nuance!

Thanks again for these great exercises!!

Collapse
 
frontendengineer profile image
Let's Code

yes, passing a function is way better and the right approach to handle setting state here. Glad that you found this post useful and you are very welcome. Will create more post/video like again.