0% found this document useful (0 votes)
10 views26 pages

Managing Local State and Remote State Slides

The document outlines the management of local and remote state in a React application, focusing on the use of hooks such as useState and useEffect for handling asynchronous calls, loading states, and error handling. It discusses best practices for making HTTP calls and introduces the concept of custom hooks. The agenda includes building a shoe store app while adhering to the rules of hooks and ensuring consistent event handling.

Uploaded by

harsh090101kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views26 pages

Managing Local State and Remote State Slides

The document outlines the management of local and remote state in a React application, focusing on the use of hooks such as useState and useEffect for handling asynchronous calls, loading states, and error handling. It discusses best practices for making HTTP calls and introduces the concept of custom hooks. The agenda includes building a shoe store app while adhering to the rules of hooks and ensuring consistent event handling.

Uploaded by

harsh090101kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

Managing Local State and

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

create-react-app VSCode Prettier


Generator Editor Code formatter
Demo Caveats

Not using PropTypes or TypeScript


Using plain CSS
I’ll provide some code to copy/paste
Implement shoe listing page
- Why state is necessary
Demo
- Fetch and store data
- Handle immutable state
- Implement filter and update state
- Display error page
- Rules of hooks
- Implement custom hook
React Hooks

We’ll use these a lot

Dedicated modules
Rules of Hooks

Only are for function components


- Can be consumed in classes too
Start with “use”
Only call them at the top level
- Consistent order
- Can’t be called inside functions,
conditionals, or loops
Breaking the 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

Only work in function components


Start with “use”
Only call them at the top level
- Consistent order
- Can’t be called inside functions,
conditionals, or loops
Need to run a hook conditionally?
Place condition inside the hook
Synthetic Events

Similar to browser’s native event system

Assures events operate consistently cross-browser

Improves performance
Event Handlers

onClick
onChange
onHover

onBlur
onSubmit
onMouseover
Etc….
When Does React Render?

State change Prop Change Parent Render Context Changes

Can skip render via: Can skip render via:


shouldComponent shouldComponentUpdate
Update React.Memo
React.Memo PureComponent
Four Ways to Handle HTTP Calls

1 Inline Call fetch/Axios/etc in your component


Not recommended
Maturity Level 1: Inline

import React, { useState, useEffect } from "react";

export default function Demo() {


const [users, setUsers] = useState([]);

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

1 Inline Call fetch/Axios/etc in your component


Not recommended

2 Centralized functions Call separate function


Maturity Level 2: Centralized Functions

export async function getUsers() {


const response = await fetch("users");
if (response.ok) return response.json();
throw response;
}
Maturity Level 2: Centralized Functions

import React, { useState, useEffect } from "react";


import { getUsers } from "./services/userService";

export default function Demo() {


const [users, setUsers] = useState([]);

useEffect(() => {
getUsers().then(json => setUsers(json))
}, []);

return users[0].username;
}
Four Ways to Handle HTTP Calls

1 Inline Call fetch/Axios/etc in your component


Not recommended

2 Centralized functions Call separate function


We just did this.
Four Ways to Handle HTTP Calls

1 Inline Call fetch/Axios/etc in your component


Not recommended

2 Centralized functions Call separate function


We just did this.

3 Custom hook Create and call your own custom hook


We’ll do this later in this module.

4 Library Call library (react-query, swr, etc)


We’ll do this in the final module.
Four Ways to Handle HTTP Calls

1 Inline Call fetch/Axios/etc in your component


Not recommended

2 Centralized functions Call separate function


We just did this.

3 Custom hook Create and call your own custom hook


Let’s do this next.

4 Library Call library (react-query, swr, etc)


Inline
import { useState, useEffect } from "react";
export default function App() {
const [products, setProducts] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);

useEffect(() => {
getProducts()
.then((resp) => resp.json())
.then((json) => setProducts(json))
.catch((err) => {
console.error(err);
throw err;
})
.finally(() => setLoading(false));
}, []);

if (loading) return "Loading...";


if (error) throw error;
return //JSX HERE
}
Custom Hook

import React from "react";


import useFetch from "./useFetch";

export default function App() {


const { data: products, loading, error } = useFetch("products");
if (loading) return "Loading...";
if (error) throw error;
return //JSX HERE
}
Maturity Level 4: Library

import React from "react";


import { getProducts } from "./services/productService";
import { useQuery } from "react-query";

export default function ReactQueryDemo() {


const { data, isLoading, error } = useQuery(”products", getProducts);
if (isLoading) return "Loading...";
if (error) throw error;
return data[0].name;
}
Local state
- useState

Summary Remote state


- useEffect
- Async calls
- Promises and async/await
- Loading state
- Declared an Error Boundary
- Error handling and Error Boundaries

Created a custom hook


Up Next:

Route State

You might also like