0% found this document useful (0 votes)
138 views41 pages

Modern React PP

This document provides an overview of a course on Modern React Redux. The course covers building a complete React-Redux application with routing and authentication. It includes a complete guide to React, Redux, React-Redux, and React-Router. Setting up authentication with JWT tokens and connecting Google and Facebook OAuth logins are also covered. The final project builds a full-stack application integrating all the concepts taught in the course.

Uploaded by

mike
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)
138 views41 pages

Modern React PP

This document provides an overview of a course on Modern React Redux. The course covers building a complete React-Redux application with routing and authentication. It includes a complete guide to React, Redux, React-Redux, and React-Router. Setting up authentication with JWT tokens and connecting Google and Facebook OAuth logins are also covered. The final project builds a full-stack application integrating all the concepts taught in the course.

Uploaded by

mike
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/ 41

Modern React Redux

What’s in the Course

★ Complete guide to React


★ In depth look at How React Works under the hood
★ Complete Guide to Redux: Reducers, Actions and Action Creators
★ How to Make Redux Work with React
★ Complete Guide to React-Router
★ In depth look at how React-Router works under the Hood
★ Google and Facebook Oauth logins
★ How to setup authentication in React-Redux with JWT tokens

We also put everything together in the final project to build a complete


front end app with React-Redux.
Course Intro
-We will put together a React-Redux app with Routing and Authentication and learn
how it works at a deep level.

-We will work directly in the development environment, we will not use JS Fiddle or
Codepen.

-I will teach you all the practical concepts

-We will focus on the main fundamental concepts of React and Redux and avoid
styling.

-I advise you not to delete code unless specified.


Overview

Outcomes: Technologies Used:

- Setup Redux Actions - React


- Setup a Redux Reducer - Redux
- Setup Action Creators - React-Redux
- Setup a React Container - Redux Thunk
Separation of Concerns
Traditional Web App: App is separated based on Single Page App: App is separated based on
programming language. Example, HTML handles components. Each component is responsible for
layout, Javascript handles all the business logic and one main functionality of the app. Example,
CSS handles styling. addpost.js component only handles submitting a
post and editpost.js is only responsible for editing
HTML, Javascript, CSS is kept in separate files. posts.

The UI layout, styling and business logic can be


contained in the same file with JSX
React
Props
- Short for Properties
- Functional Components: Accessed with the syntax “props.” (name of user defined property)
- Class Components: Accessed with the syntax “this.props” (name of user defined property)
- Part of the 1 way data binding pattern
- Read only
Components
Functional Components: Class Components:

- Set up usually as an arrow function - Set up as an ES6 JS class


- Returns JSX directly - Also referred to as containers
- Have a render function that returns
- Not aware of state
JSX
- Can have optional props - Aware of state
- Can have optional props
State
-Temporary Data

Examples: Whether a user is logged in or not, the page a user is on, or whether a dialog box is open.

Examples of Non Temporary Data: blog posts, comments and user profile data.

In React state is a Javascript object, a key-value pair.

-Changed with the setState() method.


Changing State
Done Through the setState() function

3 Aspects of changing state:

1. Do not Mutate state directly


2. Change the state by referencing the previous state.
3. React will merge the old state with the new state.
Ternary Expression
{condition ? code block if true : code block if false}
Lifecycle Methods
- ComponentDidMount()
- ComponentWillUnmount()
Redux
The three Principles of Redux
1st Principle 2nd Principle 3rd Principle

There is only one source of State is read-only. Changes are made


truth. with Pure Functions
Actions
- Redux Specific
- Can be dispatched from React
- Describe what will happen to the state
- Have a required “type” property
- Can have any other optional properties

For example, an action with the type “login_success” might change a property of Redux state called isAuthenticated
from false to true.
Action Creators
- Can dispatch actions asynchronously
- a function which dispatches a normal action
- Allows for dynamically setting the payload property
- No changes required to the reducer

For example if you want to save the user input to the state. You would setup the action creator with an arrow function like
so:

(user_input_text) => (type: “USER_INPUT”, payload: {text: user_input_text} }


Reducers
- Directly change the Redux state
- Must be “pure”, or Can’t be async
- Takes “state” and “action” as parameters
- Usually setup as a switch statement
- Each case statement has to match an action type

case ACTION_TYPES.LOGIN_SUCCESS:
return {
...state,
isAuthenticated: true,
}
mapStateToProps()
- Essentially, how to get the state from Redux
- Property in the return statement is user defined

- Set the value to “state.” (name of reducer if more than one) “ . ” (name of property from reducer)
- In the React render method use “this.props.” name of property you set.
mapDistachToProps()
- How to change the state by dispatching actions
- Actions can be plain or async action creators
- Actions can have an optional payload

- To dispatch actions use the syntax “this.props.” (name of the property you set)
connect ()
-Connects the React Container with the Redux store

Read and Actions Container Read Only Container Dispatch Actions Only Container

connect (mapStateToProps, connect (mapStateToProps)(Container) connect (null,


mapDispatchToProps)(Container) mapDispatchToProps)(Container)
React Redux React-Redux

Update State this.setState() Dispatch actions to the mapDispatchToProps()


reducer this.props.dispatch_action()
store.dispatch() Then dispatch actions to the
reducer.

Read State this.state.state_property store.getState() mapStateToProps()


this.props.state_property
Routing
Traditional vs SPA Routing
Traditional Routing: Single Page App Routing:
- Single HTML File
- Multiple HTML Files - Only 1 server request for initial web
- New server Request with each route site loading
change - A new component renders for each
- Browser Reload on each route change route change
- Relatively Slower performance - Browser does not reload with route
change
- Very fast performance
Google O-Auth setup
1. Create a Project.
2. Go to Credentials
3. Select Create Oauth Client ID
4. Setup the consent screen
5. Enter Name of Application and put auth0.com as the authorized domain
6. Save
7. Select Web Application
8. For Javascript origins put your application auth0 domain.
9. For URI redirect put your auth0 domina and add /login/callback
Facebook O-Auth setup
1. Click on Apps and hit add new app
2. Click on Facebook login
3. Next you will see the quickstart on the left hand side tab
4. Choose the web app
5. Add auth0.com to valid URLs
6. Click on the Facebook Login > settings tab in the left hand side and enter you auth0
domain in the valid 0auth redirect URIs
7. After click on the Settings > Basic tab where you will find your client id and client secret.
8. Next copy these credentials in to the auth0 dashboard.
A Complete React-Redux Frontend App
Why I didn’t cover Redux Thunk
- Any functionality offered by Redux Thunk can be accomplished without Redux Thunk
- Redux Thunk is mainly Syntax sugar, meaning it makes code slightly easier to read.
- The difference is so small that in my opinion it is not worth the time to learn it for such a
slight advantage.

Link Comparing Redux Thunk with regular action creators, the difference in code is quite literally
2 words.

https://stackoverflow.com/questions/34570758/why-do-we-need-middleware-for-async-flow-i
n-redux
Hooks
React Hooks
Hooks are referring to being able to “hook” react class functionality to a functional component.

Main purpose of hooks is to give class functionality to react functional components, mainly to
allow functional components to read and update state.

This both makes development easier and improves performance.


2 Rules of Using Hooks
1. No nested hooks calls 2. Do not call hooks outside of the
component function
Wrong:
if (true) { useEffect( () => {return value} ) }

Right:
useEffect( () => true ? return value : null )
4 Main Hooks Overview
useState() useEffect() useContext() useReducer()

Similar to this.setState(). Similar to Similar to react-redux. Similar to react-redux.


componentDidMount()
Updates local component Allows you to access and Allows you update the
state. Use when you want to update the global context local component state
call function automatically state through the React through redux actions
context API. and reducers.

DOES NOT update state


globally by itself
useState()
const [value, setValue] = useState(initalState) Variable Names are user defined

[ state value, set state function ]


Without Array destructuring:
const value = useState(0)[0]
Set State: setValue(value + 1 )
const setValue = useState(0)[1]
Read State: <p> { value } </p> in render method.
Multiple Properties:
Component re-renders automatically when state const [value, setValue] = useState(initalState)
changes. const [value2, setValue2] = useState(initalState)
useEffect()
useEffect(() => { useEffect(() => { useEffect(() => {
() => { return value } () => { return value } () => { return value }
}) }, [] ) }, [state.value] )

useEffect will be called every useEffect will be called when useEffect will be called when
the component mounts state.value changes
time a component renders
useReducer()
import * as Reducer from './store/hooks/reducer’;
Import * as ACTIONS from ‘./store/actions/actions’;

const [state, dispatch] = useReducer(Reducer.reduxReducer, Reducer.initialState)


[ value, function ]

Regular Action: dispatch(type: “ACTION”)


Action Creator: (payload) => dispatch(ACTIONS.create_action(payload))
Read State: <p>{ state.state_property } </p> in render method. Same state property that you setup in the
initial state, in the reducer.
What is Context?
- Context is separate from React Hooks
- Is a way to pass down props from a parent component to a deeply nested child component
- In regular React props can only be passed to a direct child component of a parent component.
- A parent can’t pass props to a child of a child component.
- Is what allows us to have a global state
useContext()
In separate context.js file: Import the context in your root App.js file:

const Context = React.createContext({ import Context from './utils/context';


prop1: false
}) Import and setup the actions and reducers here as
well. See the useReducer() Syntax guide for more
details.
export default Context;
useContext() cont.
In root App.js file. Wrap your routes with Provider: **Important:

<Context.Provider The “prop1” that we setup in the beginning in the


value={{ context.js file is irrelevant and is overridden here
state_prop1: false, when we initialize the provider.
update_state: () => return newValue
}} Setup up all your global state and dispatches here
<Routes /> in the root App.js file and not the context.js file.
</Context.Provider>
useContext() cont.
Import the Context into a component and initialize After initializing context you can access the global
it like so: state.

import Context from '../utils/context'; Read State: { context.state_prop1 } in render


method
const context = useContext(Context)
Set State: { () => context.update_state() } in event
handler

**You can update the global state through either useReducer() or useState() in App.js
Migration Guide from Redux to React hooks

- Actions do not need to be changed at all.


- Reducers do not need to changed either.
- Simply export both the initial state and the reducer instead of just the
reducer. Do not use “export default”
- Then Pass in both the reducer and initialState to the useReducer() hook
- Export and Import actions as normal.
- Actions are dispatched as normal
React Redux React-Redux React React React
useState() useReducer() useContext()

Update this.setState() Dispatch mapDispatchTo setValue(value) dispatch(type: {() = >


State actions to Props() ‘string of context.name_o
the reducer action’) f_property()}
store.dispatc this.props.dispa Or
h() tch_action() dispatch(ACTIO
Then dispatch NS.function())
actions to the
reducer.

Read this.state.state store.getStat mapStateToPro {name_of_prop {state.name_of {context.name_


State property e() ps() erty} _property} of_property}
Name of
this.props.state Name of Name of property comes
_property property user property comes from value prop
defined in local from Reducer of Context
component Provider
The Final Project
Building upon a existing basic React Redux App. This will allow you to see how React Hooks compare to
React - Redux side by side.

A lot of current projects still use Redux so it’s important to understand both approaches.

We will not change the existing React Redux code but build React Hooks separately from scratch

You might also like