- Don’t call Hooks inside loops, conditions, or nested functions
- Only Call Hooks from React Functions
- State updates are batched!
- States are immutable
To update a component with new data, two things need to happen:
- Retain the data between renders.
- Trigger React to render the component with new data (re-rendering).
This means that you shouldn’t reassign items inside an array like
arr = 'bird', and you also shouldn’t use methods that mutate the array, such as
Instead, every time you want to update an array, you’ll want to pass a new array to your state setting function. To do that, you can create a new array from the original array in your state by calling its non-mutating methods like
map(). Then you can set your state to the resulting new array.
- When you store objects in state, mutating them will not trigger renders and will change the state in previous render “snapshots”.
- Instead of mutating an object, create a new version of it, and trigger a re-render by setting state to it.
In general, you should only mutate objects that you have just created. If you were inserting a new artwork, you could mutate it, but if you’re dealing with something that’s already in state, you need to make a copy.
Spread syntax (
...) allows an iterable, such as an array or string, to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected. In an object literal, the spread syntax enumerates the properties of an object and adds the key-value pairs to the object being created.
useState Hook provides those two things:
- A state variable to retain the data between renders.
- A state setter function to update the variable and trigger React to render the component again.