1. Forget that setState is asynchronous
Even experienced folks forget about that.
Let’s take a look at this example.
Always keep in mind:
setState is async. setState is async. setState is async.
As you can see from the example above we can safely call any function after state is updated via setState callback.
setState({ age: value }, () => {
// state is updated and you can safely perfom any action
// here
})
2. Forget how setState works in functional components
If you’re just starting with React hooks, you can easily forget that setState here doesn’t work the same way as in the class components.
setState
from class components automatically merges the previous state with the new one.
setState
from functional components don’t do this.
The right way to use setState in functional components is to combine previous state value with the new updates.
3. Using React when you don’t need it
Love this.
Remember: You don’t need ReactJS in most cases.
One page app? Don’t need it.
Blog? Don’t need it.
Large complex app? It depends.
Learn the basics first. And you will understand when and why you need to use React.
In the end
Choose technologies by the problem you try to solve.
Don’t choose something because it’s popular right now.
That’s all. Thanks!
Top comments (7)
Great! Thanks for sharing.
I've got error in example 2 - Cannot read property 'value' of null here
onChange={(e) =>setState((prevState) => ({...prevState,age: e.target.value}))
looks like
onChange={(e) =>setState((prevState) => ({...prevState,age: e.target && e.target.value}))
woud fix this issue.
In your "Forget that setState is asynchronous" example, do you need the second
this.checkAge()
in the "right"updateAge()
method?No, that's a typo. Thanks for pointing out!
One Page App : my best choice is react. We do lot of small promotional application without react, but the truth is: react is much simpler than pure js with html handling.
Yes, it's simpler to manage all event handling and logic with react, but it has downsides – size.
If application size is critical for you, you should choose another way to build your app.
If I faced application size problem, then I choose preact instead react which is generate smaller size, near same functionality
Preact library is smaller than React.
But in most cases, the size of the generated bundle will be not less.