React JS
What is React ?
• Developed by Facebook in 2013. (Jordan Walke)
• A JavaScript library for building User Interfaces.
Why React ?
Angular vs React vs Vue
ANGULAR REACT VUE
• Framework • Library • Library
• Developed by Google • Developed by Facebook • Open-Source Project
• Typescript • JSX • HTML & JavaScript
• Develop Native, Hybrid • Develop SPA & • Develop SPA &
& Web apps Mobile Apps Native Apps
• MVC architecture • Virtual DOM • Virtual DOM
Features of React JS
• Based on component structure
• Uses JSX ( Extension of JavaScript )
• Best used for SPA (Single Page Applications)
• Utilises both Virtual DOM and Real DOM
Environment Setup
• Step 1 : Install Node.js
• Step 2 : npm install -g create-react-app
• Step 3 : npx create-react-app <app_name>
Document Object Model
Nav Bar
Courses Profile
DSA FSD Signup
Virtual DOM
Virtual
DOM
State Change Compute Diff Re-render
Browser
DOM
JavaScript Executable ( JSX )
• Syntax Extension to JavaScript.
• Produces React “elements”.
React without JSX
createElement() definition Representation of Object Created
React with JSX
JavaScript Executable ( JSX )
• JSX can be used for
• Embedding Expression
• Specifying Attributes
• Represent Objects
And many more tasks…..
create-react-app
• Less to Learn
• Only one dependency
• No lock in
Ways to Create Components
• Class Components
Ways to Create Components
• Function Components
Functional vs Class Components
Functional Components Class Components
• Pure JavaScript function • Class that extends properties from
React.Component
• No render Method • render() method is mandatory
• Stateless Components • Stateful Component
• React Lifecycle methods • React lifecycle methods can be used
cannot be used
Functional vs Class Components
Functional Components Class Components
• Hooks can be easily used • Hooks can be used with different syntax
• No State Variables • Contains State Variables
Props
• Arguments passed into React Components
• React is pretty flexible but it has a single strict rule:
“All React components must act like pure functions with respect to their props.”
• Pure Functions don’t attempt to change their inputs , i.e. they are immutable
Props
State
• Build-in React Object
• Used to contain data or information about component
• State can change over time
• On change of state , the component re-renders
• A state can be modified based on user action or network changes
• this.setState() is used to change the value of the state object
setState()
Props Vs State
State Props
• State is used to store the data • Props are used to pass data and
Use Case of the components that have to event handlers to the children
be rendered to the view components
• State holds the data and can • Props are immutable—once set,
Mutability
change over time props cannot be changed
• State can only be used in class • Props can be used in both
Component
components functional and class components
• Event handlers generally • The parent component sets props
Updation
update state for the children components
Event Listeners
• Functions that listen for some events happening and execute when that event happens.
• React events are usually written in camelCase
• React event handlers are written inside of curly braces.
• Arguments are passed to event handlers using an arrow function
React Context API
App App
Users Users
User info User info
Without Context API With Context API
React Context API
• React.createContext()
• Context.Provider
• Class.contextType
• Context.Consumer
• Context.displayName
React Life Cycle
Conditional Rendering
• Rendering the components in react can be conditional.
• There are many ways to achieve this as :
• Logical && Operator
• If-else
• Ternary Operator
• Switch-case
High Order Components
• HOC is a function which takes a Wrapped component as input argument and returns a
new Enhanced component
• It should always be a pure function.
• It should never modify the Wrapped Component.
Pure Components
• Component is Pure if
• Return value is only determined by it’s input values
• It’s return value is always the same for the same input values
• Class components that extend the React.PureComponent class are treated as pure
components
Pure Components
Pure Components
• Pure Components prevents components being re-rendered if the values of state and
props has not changed.
• These components will be rendered only in 3 conditions:
• this.setState({ })
• Change in props
• this.forceUpdate( )
• Exception : shouldComponentUpdate
React Forms
• Controlled Components
• Uncontrolled Components
Form Elements
• The input Tag
• The textarea Tag
• The select Tag
• The file input Tag
Handling Multiple Inputs
• Multiple inputs are handled by using name Attribute
• To access the fields in the event handler use the event.target.name and
event.target.value syntax.
React Router
Multi page Application
Single page Application
React Router
react-router-dom
react-router-native
React Router
Types of Routers
• BrowserRouter
• HashRouter
• MemoryRouter
• NativeRouter
• StaticRouter
React Router
Data Routers
• createBrowserRouter
• createMemoryRouter
• createHashRouter
Implementing Routing
• Step 1 : Wrap Component with a Router
Implementing Routing
• Step 2 : Set-up Routes and Route.
React Router
Components
• Link
• NavLink
• Navigate
• Outlet
React Router
More on Routing
• Dynamic Segment
• Splat / MatchAll
• Routing Priority
• Nesting Routes
React Router
Hooks
• useRoutes
• useParams
• useHistory
• useLocation
• useOutlet
• useOutletContext
React Hooks
• Allows use of state and other features in Functional Components
• Hooks are functions that let you “hook into” React state and lifecycle
features from function components
• Types of Hooks
- State Hook
- Effect Hook
- Context Hook
State Hook
useState()
[currStateValue,updatefunction]
State Hook
Problem Statement : Create A Counter App using useState()
useState() Hook
Effect Hook
• Adds the ability to perform side effects from a function component
• These Side effects can be
- Data Fetching
- Subscriptions
- Manually Changing DOM , etc.
• Serves the same purpose as componentDidMount, componentDidUpdate
and componentWillUnMount.
Effect Hook
Problem Statement : Update Document title using useEffect() on
the Counter App.
Effect Hook
Context Hook
• Accepts a context object and returns the current context value for that
context
• When the nearest <MyContext.Provider> above the component updates,
this Hook will trigger a re-render with the latest context value passed to
that MyContext provider.
• A component calling useContext will always re-render when the context
value changes.
Context Hook
Problem Statement : Change Theme of a Button element called
ThemedButton on change of context value. The button is a Child
component of a component called SignUp and SignUp is a Child
component of App Component.
Redux
• Pattern/Library for managing and updating application state, using events
called ‘actions’ .
• Helps manage ‘GLOBAL’ state
When to use Redux
• You have large amounts of application state that are needed in many
places in the app
• The app state is updated frequently over time
• The logic to update that state may be complex
• The app has a medium or large-sized codebase, and might be worked on
by many people
State Management
Redux Terminologies
• Action
• Action Creators
• Reducers
• Store
• Dispatch
• Selectors
Redux Application Data Flow
Redux Application Data Flow
• State describes the condition of the app at a point in time, and UI renders based on
that state
• When something happens in the app:
The UI dispatches an action
The store runs the reducers, and the state is updated based on what occurred
The store notifies the UI that the state has changed
• The UI re-renders based on the new state
Redux
Problem Statement : Create a Custom Increment App using Redux .
Redux Toolkit
• Redux Toolkit is a set of tools that helps simplify Redux development.
• Includes utilities for creating and managing Redux stores, as well as for writing
Redux actions and reducers.
• Initialization
Redux Toolkit
• Create a Redux store with configureStore
- configureStore accepts a reducer function as a named argument
- configureStore automatically sets up the store with good default settings
• Provide the Redux store to the React application components
- Put a React-Redux <Provider> component around your <App />
- Pass the Redux store as <Provider store={store}>
Redux Toolkit
• Create a Redux "slice" reducer with createSlice
- Call createSlice with a string name, an initial state, and named reducer functions
- Reducer functions may "mutate" the state using Immer
- Export the generated slice reducer and action creators
• Use the React-Redux useSelector/useDispatch hooks in React components
- Read data from the store with the useSelector hook
- Get the dispatch function with the useDispatch hook, and dispatch actions as needed
Axios
• HTTP Client Library
• Promise Based
• Allows to make requests to a given endpoint.
• Installation :
Sending HTTP Request
• axios() Function
• Configuration Options
- method: The HTTP method through which the
request should be sent in
- url: The server's URL to which the request must
be sent to
- data: The data specified with this option is sent
in the body of the HTTP request in Axios POST
requests, PUT, and PATCH.
Axios Request Methods
• axios.request(config)
• axios.get(url[, config])
• axios.delete(url[, config])
• axios.head(url[, config])
• axios.options(url[, config])
• axios.post(url[, data[, config]])
• axios.put(url[, data[, config]])
• axios.patch(url[, data[, config]])
Axios Response Objects
• data - the payload returned from the server
• status - the HTTP code returned from the server
• statusText - the HTTP status message returned by the server
• headers - headers sent by the server
• config - the original request configuration
• request - the request object
Axios Post Request
axios.post(“url”,Data Objects)
Axios Get Request
axios.
get(‘u
conso rl’).the
le.log. n(func
}) (respo tion(re
nses ) spons
e){
Babel
Babel
• @babel/core
• @babel/preset-react
• @babel/preset-env
• Babel-loader
Webpack
Index.html Copy Index.html
Includes Includes
JavaScript Files
Bundle Files
(in ES6 !) Bundle Transpile
Source Webpack Output
Webpack
• webpack
• webpack-dev-server
• html-webpack-plugin