React Native II Flashcards
What are we going to learn in React Native II?

Mosh worked really hard on this course
Promise you’ll be a React-Native Ninja
Tons of Tips and Tricks
If we build an App or get a job, share story!
Advanced Concepts:
Native Device features (Android/iOS)
Navigation
Networking (Api calls)
Offline support
Authentication & Authorization
Push Notifications
Distrubution (App stores)

What do we need to know?
Ultimate React Native Part I
React Hooks
(useState, useEffect, custom hooks)
React Context
Javascript
(arrow fns, spread, async/await)
What native features are not available in React Native?
React Native has limited API for working with native features:
Camera, context not available
available as 3rd party library
Ex. image picker -> allows us to get an image from camera
have to install a library
run in iOS project
can eject from expo
or
use components by expo
lots of native features available

What is the ImagePicker component?
Can select a video or image from user’s library or camera
expo install expo-image-picker
What is useEffect (effect hook) for?
accessing lifecycle hooks like componentDidMount ( ) in functional component

How can we access a user’s camera?
ImagePicker component from ‘expo-image-picker’

What is the permissions API?

another method for accessing camera, etc.
can pass multiple permission types

How can we access a user’s library to add a photo and display on the screen?

useState() hook
to set result.uri (from ImagePicker)
display imageUri in Image component

How do we build a re-usable ImageInput component?


How do we handle the touch event of our image picker component?
consumer of ImageInput:
handles state using hooks
ImageInput:
props - imageUri, onChangeInput (reference to hook from consumer for updating data of imageUri)
wrap in a TouchableWithoutFeedback
set handlePress to fn for calling ImagePicker.launchImageLibrary

How do we build the image input list component?


How do we solve this problem?
Hint: Horizontal scrolling

ScrollView component from react-native

wrap ScrollView in a View so it only takes up content space
use useRef() hook to get current element and scroll to end
How do we design a form image picker?
wrap our ImageInputList in a new component with an error message
Just like FormPicker, FormField
allow Formik to handle state
use the values field to get form values
use the SetFieldValue method to update form values

How do we add the Form Image Picker to our Listing Edit Screen?

Consume FormImagePicker in ListingEditScreen
add validation to images using Yup schema in ListingEditScreen

How do we get the user’s location?
define function:
getLocation( ) to async call Location.getLastKnownPosition()
useEffect :
to call getLocation( )
useState:
set location and get location

What is a custom hook?
Encapsulate some state and logic around state
in a re-usable component
naming convention:
useLocation
*start with “use”

What are we going to learn in navigation?

How to take App to next level
add navigation at bottom
can click on screens
App is becoming more functional
How do we implement navigation in our React Native Apps?

What kind of navigators do we have in React?
Stack - taking users from one page to another
Tab - going between tabs
Drawer - drawing things on screen navigations
**all of them are very similar and can learn if you know one!

How do we use the stack navigator?

Each navigator is implemented in a separate library

We render StackNavigatorComponent
it knows how to navigate between components
What does React Navigation give our screen components?

A special prop called navigation
can destructure and pick navigation property
Ex. navigation.navigate(“Target Location”)
only available in screen component
not available in child components
.push creates a new instance on the stack
.navigate creates a single instance on stack
but can use navigation hook to access navigation object

How do we access navigation prop using React Navigator hook?
useNavigation( ) hook

How do we pass parameters to React Navigator?
ex. pass ID of a specific tweet

How can we set the title of a screen?

using the options prop of the Stack.Screen component

How do we customize the header of a screen?

Locally (screen only)
use the options prop of the Stack.Screen component
headerStyle (pass a color)
headerTintColor
headerShown
Globally (all screens)
options prop of the Stack.Navigator component
can override for specific screen

How do we create a bottom tab navigator?

npm install @react-navigation/bottom-tabs
createBottomTabNavigator()
returns an object
has Screen and Navigator properties
render
TabNavigator inside NavigationContainer

How do we add a background color to each tab and change the text when pressed?
createBottomTabNavigator()
tabBarOptions = styles
/>

How can we add icons to our Tabs?
Really easy
Tab.Screen
options - set to a fn that renders a MaterialCommunityIcon
destructure the props from React Navigator
set size and color to props given by Navigator

What is nesting navigators?
instead of passing a component to the Tab.Screen component (bottomTabNavigator)
passing a Stack Navigator
called nesting navigators

How do we build the welcome screen to login screen / register screen navigation?
AuthNavigator.js
use createStackNavigator( ) from @react-navigation/stack
from the return object
create Screen component and Navigator container
Consuming Screen:
inherits navigation prop
uses navigate method onPress of button

How do we set a custom theme for our app?
spread the …DefaultTheme

can update headers in Stack.Screen
pass options prop
headerStyle: { backgroundColor: ‘white’ }
How do we create the AppNavigator component?


How do we create navigation from the listings screen to press on an item and be directed to the item details screen?

add TouchableWithoutFeedback to card component
assign the onPress event via props to consuming class
because we have registered the screen with our navigator….
can access the navigation or route props
handle onPress in ListingScreen by extracting navigation prop (ListingsScreen)
extract route param, use it to get item
listing.title, listing.price
dynamically display item

How can we navigate to an item dynamically?

wrap card component in a Touchable
set the event to props (onPress)
handle in ListingsScreen (navigation prop)
handle ListingDetailsScreen (route to get item[param])

How do we make our listing details screen appear from the bottom vs from the side?

Set Stack.Navigator prop to modal

What does our account screen need?

It’s own stack navigator for navigating to it’s components

How do we make our AppNavigator tabs beautiful?

create NewListingButton component
let consumer decide what should happen when onPress event
hook with prop

What should we do to make our navigation cleaner?

Get ride of hard coded route names
if there is a typo, app will not work
testing every feature manually or automated
if rename route, have to rename all instances
solns?
store all routes in a single place in app
Object.freeze ensures object cannnot be modified anywhere else in our app

What are we going to learn in the networking section?
How to connect our React-Native app to a node.js server

created a fake database
Why?
Don’t need to setup MongoDB, etc.
What library are we going to use for calling APIs?
Hint: npm i apisauce

Api Sauce
an abstraction over axios
can use fetch API, but using api sauce
why?
whenever call server, promise always resolved, even if an error
just check if there is an error
no try/catch needed
gives us standardized errors

What should our components know?

What UI looks like
How UI behaves
Why?
separation of concerns
NOT:
HTTP protocol
calling GET, POST, ETC.
not responsibility of component
Don’t do this, violates separation of concerns
Soln?
Create an API layer that handles all this
proper architecture

How do we create our basic API layer?

How can we get the list of items from our backend?

How do we debug our API calls to see if the server was called as well as the request and response objects?

Look at network requests in React Native Debugger

How should we handle an error?
should provide a good user experience
Not a blank screen
How?
use another hook to catch an error from APISauce
conditionally render the error with a Text component
and a Button component

How do we simulate a slow network connection?
React native developer tools
makes our app slow
takes 2 seconds of a blank screen before listings
soln?
Show an animation before listings shown

How do we display an activity indicator?

ActivityIndicator component
defined in react native core
use a separate hook for loading, setLoading
render component if loading is true
kind of boring can replace with a beautiful animation

What is Lottie?

an animation library built by AirBnB
Can add beautiful animations
JSON file exported from Adobe After Effects
LottieFiles.com
thousands of animations made by people
most free, some paid

How can we add a beautiful Lottie animation to our application?
Hint: expo install lottie-react-native

Go to LottieFiles.com
customize a free animation
download the JSON
upload into project
render using a special component

What’s the problem with this implementation?

have to repeat logic everytime want to call server
declare hooks, etc.
is there a better way?
repetative, redundant
Soln?
use hooks
encapsulate some state and logic around
can encapsulate details around a re-usable hook

How do we create a re-useable API hook?
extract the useState (state)
extract the logic that modifies state

How do we pass props to our re-usable useApi hook?
use rest operator to allow request function in useApi
to take zero or more args

How can we call multiple Api’s in on a screen?
name each Api call and pass to useApi function

How do we post data to the server?
(ie - send a new listing to the server?)

How do we get upload progress?
pass a third object to axios (config)
{onUploadProgress: progress => console.log(progress)}
this object contains loaded and total bytes
(loaded bytes / total bytes) * 100 = progress
How?
Pass fn reference to child (raising event)
child calls event when event is raised
gives access to progress in UI layer

How do we build the upload screen?
UploadScreen
composed of a Modal
Props of progress, visible
ListingEditScreen
composed of UploadScreen
uses hooks to handle progress, visibility

How do we add a beautiful progress animation to our application?
npm install react-native-progress –save
hook for storing progress / visible
pass progress / visible to UploadScreen
in UploadScreen import progress bar

How do we display a beautiful done animation?
UploadScreen
conditionally render
Progress.Bar or LottieView
raise onDone event after onAnimationFinish
ListingEditScreen
handle onDone event

How do we reset our form after making a post to the server?
pass resetForm from formik (fn)
ensure FormFields use formik setFieldValue, value from FormikContext so that resetForm can clear values

What will we learn in the offline support section?
A very important topic
lots of otherbooks / courses overlook topic
What?
if no internet connection
reloads listings from a cache

What are strategies for offline capable apps?
*as we build more offline capability, cost increases
Think about time, budget, uses before implementing in apps
Four Strategies:
Notify the user
that there is no internet connection
Disable features
turn off certain feature capabilities while offline
Cache data
data available while offline
Store user actions
if user takes actions, store actions locally on device
when online is back, execute them on server

How do we detect the status of a users network connection?

expo install @react-native-community/netinfo
NetInfo.fetch() returns an object…
isInternetReachable
check this property
isConnected
doesn’t mean has internet

How can we subscribe to network status changes?

Class Components:
ComponentDidMount
call const unsubscribe = NetInfo.addEventListener()
Function called everytime a change to network status
ComponentDidUnmount
unsubscribe ( )
prevent memory leaks
Functional Components
useNetInfo ( ) hook
subscribe / unsubscribe happens inside hook

What is caching?
When we call an API to retrieve data from server
storing successful request data locally on device, so if mobile device goes offline
can read data from cache
How?
AsyncStorage -

What are the three options for caching successful API response data locally on the mobile device?

AsyncStorage
values are not encrypted
like local storage in browsers
stores key value pairs
values are strings, not encrypted
6MB limited storage
don’t store large data or sensitive data
SecureStore
expo built API
2MB limit
SQLite
SQL like database
if query data using SQL, use this option

How do we store a value in async storage?
Hint: expo install @react-native-community/async-storage

How can we debug our async storage in React Native debugger?
open react native debugger
in console
call showAsyncStorageContentInDev()
work directly with Async functions
$reactNative.AsyncStorage.clear()
if storage is corrupt, need to clear, or insert values

How do we store listings in cache in our app so that if the network connection is down we can read data from our cache?

caching listings:
don’t have complex data to query
don’t have sensitive information
use AsynStorage
How does AsyncStorage work under the hood?
We don’t have to worry about these implementation details
just store in AsyncStorage and let them figure out the details
hide behind a cache layer (don’t use directly)
Android
uses SQLite
iOS
uses dictionary (hash map) or separate files

What is a cache layer?

abstraction over AsyncStorage
will handle serialization / de-serialization logic
will apply a timestamp (expired or not)
automatically remove expired data
Why?
Encapsulate all details in a single place
Prevents data leakage
minimizes breaking changes if we change cache implementation
What is the command-query separation (CQS)?

an important programming principle
functions should either be commands or queries
Command
fn that changes state of system
Query
fn that returns the state of the system
What’s the problem with this code?

it breaks the command query separation principle
the function is both returning the state and changing the state in the same function
But…
we are consciously breaking the rules
we don’t want to store too much data in the cache
What’s the problem with this code?

it’s violating the single responsibility principle
fn or method should have a single responsibility
get ( ) function has two responsibilities:
- get item from cache
- detecting if item is expired or not
Soln?
move logic somewhere else
define new function isExpired()
How do we bring the caching layer into the api layer?

in the client.js file
logic for caching should go where calling server
store get method in a constant
call original get ( )
perform some logic before / after

How do we cache images?

Hint:
npm i react-native-expo-image-cache
npm i expo-blur
popular library gives replacement imagecomponent
(vs react native image component)
Why?
Supports caching, progress loading, authorization headers
But?
Not available for expo aps
Soln?
react-native-expo-image-cache
How can we cache images in our app?

use Image component from expo-image-cache
slighly different API
images now stored in files on device

What is Redux?

Used in React and React Native Apps
many people use Redux for caching and offline support
store entire app state in a single object
like a database for front end
redux-persist
persist and rehydrate a redux store
BUT…
Many people can’t live without redux
it brings extra complexity
simplicity is the ultimate sophistication

Why is using Redux not an elegant solution to caching problem?
Adds a lot more complexity
Ask yourself..
Does undue/redue really matter for your app?
know state of app and go back in time really matter?
Only use Redux if you have a complex data flow in your app
don’t use redux for every single app
When use?
When having multiple screens, sharing data, updating
Screens must be in synch
otherwise, don’t use redux

How can we store user’s actions and execute when back online?
store post request locally in app, execute later
modify API layer - post, put methods to execute later
complex app with various apps?
complex actions to handle like retrying actions, conflict resolution, optimistic updates
don’t implement by hand
use Firebase
real time database, offline support, auto synchronization
Fire saves changes automatically
Firebase would be backend of app
use Realm
automatically synchs with database
ask?
Is this necessary for my application
Twitter doesn’t allow posting tweets when offline

How do we display a notice to the user if the mobile device is not connected to the internet?
useNetInfo ( ) hook

What will we learn in the authentication and authorization section?
Users will be able to register and login
taking App to the next level
Why should we subscribe to React context vs. use Redux?
React Context replaces prop drilling
Redux is useful for large objects that change frequently
Why?
any changes to a context object, causes entire app tree to re-render
redux store components subscribe individually
only components that use / need data are re-rendered

How do we login a user?
create an auth.js api file
use client (abstraction over apiSauce)
to call endpoint and pass email, password
LoginScreen
onSubmit (handleSubmit)
define login for handleSubmit
use authApi to login by sending email / password from form
if error, use state variable to display error message

How do we decode the JWT sent from the server to access the payload?

npm i jwt-decode

How do we give the current user to all the screens in our application?
wrap in Context (react context)
pass hook (user, setUser) to all components using context

How do we replace the hard coded data in the account screen with the current user?

get user from context
useContext(AuthContext)

How do we implement logging a user out?
AccountScreen
extract setUser from context
onPress () => setUser(null)
redirects to the login / register page

How do we persist the authentication?

Auth Context vs. SecureStorage
two places in memory to persist
store auth token on device
use Secure Store
storage.js
responsible for storing / retrieving auth token
like AsynStorage but for secure data

What is the AppLoading component?


What is the problem with this code?

App component
should be like a manager
delegating, not implementing
too many details of authentication inside App
Soln?
Refactoring by moving logic to auth module

How can we make this code better?

All business logic into custom hook
App is only responsible for delegation
How?
extract useContext(AuthContext)
into a module that abstracts these details
instead of importing the context hook
and the authContext hook
only import custom hook
Encapsulate
setUser()
authStorage.removeToken()
into custom hook

How can we refactor this code?

separate concerns
encapsulate logic for logIn ( )
fn updates Context and SecureStorage
both are encapsulated in custom hook
handle logic around the state there
export logIn function
import in LoginScreen
cleaner code

How can we access protected routes?

update client.js
transform (middleware) request
automatically include authToken

How do we register a new user?
usersApi
create users.js in api module
handles calling api
RegisterScreen
pass formik object (userInfo) to usersApi
How?
Register user
usersApi.register(userInfo)
formik object
Login user
authApi.login

How do we add an overlay to the listing screen?

How can we send push notifications?
Expo Push Notification
simplest
hides all complexity
by far the best
OneSignal, Amazon, etc.
have to eject from expo
make changes to native projects
lots of extra work
if you miss any steps, don’t work
review all the steps
Recommendation?
Use expo unless job says you have to use something else

What is Amazon Simple Notification Service?

have to make changes to native projects
to setup notifications
any steps missed or not done properly
have to review all steps, painfully

What are the four steps we need to execute to setup push notifications using expo?
Register app with expo
get push notification token
uniquely identifies each device
can send notification to unique device
store token on device
somewhere stored a collection of users
each user - Id, name, email, pushNotificationToken
can send notifications to a user or group of users
Send notification
happens on server
not on the client
UI has a box for typing a message
onSubmit sent to server
server stores message in DB
server notifies user
Handle device recieved notifications
decide what to do when user taps notification

How do we handle push notifications in our app?
using expo notifications

How do we get the push token?
use Permissions to ask permission
use Notifications to getExpoPushTokenAsync( )
useEffect ( ) hook
call a function
Permissions.askAsync
await Notifications.getExpoPushTokenAsync()
user will get same push token
unless they re-install the app

How do we send a notification token to the server?

AppNavigator component
ask permissions for push notifications
generate a push notification token
send it to the server using expoPushTokensApi
an abstraction over the client (axios)

How do we send test notifications in Expo during development?

How does the backend send push notifications using expo?

How can we handle push notifications in our app?

addNotificationRecievedListener

How can we navigate a user to a specific page when the notification is recieved?

Can’t?
use navigation prop
useNavigation hook
Why?
Only available in screens wrapped in Navigator
Soln?
create a reference object (ref to Navigation)
from that reference, can access navigation object
access ref property ‘current’
get access to navigation object
rootNavigation.js file
ref object called when Navigation container created
check if .current is null (will throw error if called too early)

What is the challenge with this code?

the notifications logic:
getting users permission
generating a pushToken
handling a notification response
is polluting our AppNavigator component
UI components should only have logic for presentation
Soln?
extract logic into a custom hook (re-usable)

How can we make this code re-usable?

we don’t want to hardcode the action everytime a listener is added

pass action down to component via props
What are the two types of notifications?
Remote (push)
sent by expo backend
Local
created locally in the app

How can we schedule a local notification for the future?
Ex. 10 minutes after reached cart page?

How do we send a message to the seller and display a notification for the user?

create a new form component
import Form (Formik abstraction)
FormField (error handling, etc.)
handleSubmit ( )
send message to server with messagesApi (client abstraction)
use Expo notifications to send user notification

What will we learn in the final section of this course?
how to submit app to iOS store
GooglePlay store should be similar
Have to give app proper Icon

How do we create a proper app icon for distributing our app?

https://developer.apple.com/design/human-interface-guidelines/ios/icons-and-images/app-icon/
https://developer.android.com/guide/practices/ui_guidelines/icon_design_adaptive
How do we optimize the assets in our project?
Delete non essential assets
Why?
Bundled in app during production
only make our app larger
Soln?
include only absolute essential assets
assets that must be immediately available when starting our app
anything not essential, downloaded later from internet

How else can we optimize our assets before building the app for production?
sudo npm i -g sharp-cli
Why?
reduce the size of our images
How?
npx expo-optimize
Why?
uses sharp cli behind scenes
reduces images without losing quality

What happens when we build our app?
all our javascript code gets combined, minified into a bundle
app loads, bundle is loaded into memory
Javascript virtual machine on mobile, parses code
Why?
More code in the bundle, more time to load and parse

As a best practice, what should we do?
Always check:
is there a more lightweight version of a package used?
Ex. Moment.js
bringing a lot of code we don’t need
in app, only using once, using a small functionality
moment has a lot of functionality, not used
Soln?
Replace with a more lightweight library
npm i dayjs

How can we see the cost of our import statements?

cost of moment.js is 258k (71kb compressed)

vs.
7.2k kb for dayjs (compressed)
What else can effect our bundle size?
How we import things from a library
Why?
can import needed code vs. all library code
How?
some libraries are split into small packages

How can we log errors when our app is in the app store?

use error reporting tools
Talked about sentry in React course
LOVES bugsnap (new tool)
a bit pricey
report handle / unhandled
identify users who encountered errors

What is bugsnag?

an error reporting tool
Mosh loves it!
Lift, Square, Airbnb, Mailchimp
How?
upload sourcemaps allows us to see stack trace in production

How do we report errors in our production app?

use bugsnag
create logger.js (in utility) folder
can see error rate over time (very powerful)
can see device iOS and version of React (very powerful)

How can we manage the settings for different environments?

Why?
baseUrl is for production backend
in production app, want to use backend hosted in cloud
How?
settings.js (config module)
define settings for different environments

How do we publish to expo?

publish on Expo
expo publish –release-channel staging
build standalone binaries for iOS and Android

How can we build standalone binaries for deployment to app stores (Google and Apple)?
Expo publishing only used for dev, testing
Why?
don’t want users to have to download expo app to use our app
soln?
Expo’s build service
Mosh absolutely loves this service
it’s exceptional
How can we build the iOS standalone app?

Step 1: register in Apple developer program
developer.apple.com/programs/enroll
must provide driver’s license
must pay $99 / year
to publish to app store, need current payment status
Step 2: add fields in app.json (app store uses)
bundleIdentifier
buildNumber
Step 3: expo build:ios
(terminal)
appleID, password
create distribution service
apple push notifications key
provisioning profile
Step 4: Download ipa file (monitor status)
for uploading in app store
How do we submit our ipa file to the app store?
Hint: file containing our app from expo build:ios
Step 1: appstoreconnect.apple/com
login with appleID
go to “my apps”
create new app
Step 2: install Transporter (from apple app store)
for uploading app to appstore
deliver it to app store
can invite users by email to test app, testers
must download testflight, then download app on phone
Step 3: prepare for submission
provide screen shots, url, etc.
takes 1 day or 2 or make changes

What is over the air updates?

don’t have to re-submit to app store
App will check expo and automatically download updates

What are the next steps?
think of next app idea
apply for a job as a React native developer
should have very strong foundation
be able to discover new things
if get a job or build an app, share a tweet with him
he wants to know he made an impact on our life
Salary:
Average $120,000 usd / year
entry level positions start at $80,000 usd /year
experienced $187,000 usd /year
