managing-shared-derived-and-immutable-state-slides
managing-shared-derived-and-immutable-state-slides
Cory House
React Consultant and Trainer
@housecor | www.reactconsulting.com
Build shopping cart
- Derive state
Demo
- Explore where to declare state
- Lift state
- Immutability
• Why bother?
• Immutable friendly approaches
- Use function form of setState
- Declare event handlers on a list
Where to Declare State
Common mistake
Declaring state in the wrong spot
Sign
Hard to consume and share
Suggestion
Start local, and lift when needed
Principle of Least Privilege
Every module must be able to access only the information
and resources that are necessary for its legitimate purpose.
Ideally each React component only has access to the data/functions it needs
State: Start Local
App
Fast comparisons
Pure funcs are easy to understand and test
Simpler undo/redo
Avoids bugs
Immutability = Performance
Function React.memo,
Class shouldComponentUpdate, PureComponent
Immutability:
Number Objects
String Arrays
Boolean Functions
Undefined
Null
state = { t Current State
role: 'author’
return state;
state = { t Current State
role: 'author’
role: 'admin'
}
Handling Immutable Data in JavaScript
Create an empty
Then add these properties
object…
Copy via Spread
const user = {
name: 'Cory’,
address: {
state: 'California’
}
}
const user = {
name: "Cory",
email: "[email protected]",
address: {
city: "Chicago"
}
}
// Avoid
const [user, setUser] = useState(user);
// Prefer
const [user, setUser] = useState(user);
const [address, setAddress] = useState(user.address);
Warning: Only Clone What Changes
You might be tempted to use deep merging tools like clone-deep,
or lodash.merge, but avoid blindly deep cloning.
Here’s why:
Avoid VS Prefer
push map
pop Must clone array first filter
reverse reduce
concat
spread
Handling Immutable State
Benefits VS Downsides
Limited storage
Local
Security risk
Simple
localStorage / sessionStorage block
Fast
I/O
Works offline
Tied to single browser
Derive state when possible
Form Validation