Managing Local State and Remote State Slides
Managing Local State and Remote State Slides
Remote State
Cory House
React Consultant and Trainer
@housecor | reactjsconsulting.com
Build a shoe store app
Local state
Agenda
- useState
Remote State
- Use useEffect for async calls
- Loading state
- Error handling and error boundaries
- Promises and async/await
- Custom Hooks
Installs
Git Node
Source Control JavaScript outside the browser
git-scm.com nodejs.org
Node 16+ required
Check Your version: node -v
Demo Setup
Dedicated modules
Rules of Hooks
Nav.is Nav.is
function Nav() {
let on = false;
let setOn = () => {};
function Nav(props) {
// WRONG. Can't wrap in conditionals function enableAdmin() {
if (props.isAdmin) { // WRONG. Can't nest in func.
const [role, setRole] = useState(''); [on, setOn] = useState(false);
} }
// ...
} return (
<button onClick={enableAdmin}>
Enable admin
</button>
);
}
Rules of Hooks
Improves performance
Event Handlers
onClick
onChange
onHover
onBlur
onSubmit
onMouseover
Etc….
When Does React Render?
useEffect(() => {
fetch(`users`)
.then(resp => resp.json() Inline calls are hard to
.then(json => setUsers(json)); handle consistently across
}, []); the app.
return users[0].name;
}
Four Ways to Handle HTTP Calls
useEffect(() => {
getUsers().then(json => setUsers(json))
}, []);
return users[0].username;
}
Four Ways to Handle HTTP Calls
useEffect(() => {
getProducts()
.then((resp) => resp.json())
.then((json) => setProducts(json))
.catch((err) => {
console.error(err);
throw err;
})
.finally(() => setLoading(false));
}, []);
Route State