Kickstart to ReactJS
GDSC NIT Silchar
React is a JavaScript library for building user interfaces.
What is ReactJS..??
Is it worth to learn?
Market needs React Devs !!
So why not become one..?
In today’s Session
• React Setup
• Components and Its types
• What’s JSX..?
• Using JS in HTML
• Importing CSS and CSS Modules
• Props
• Hooks!!
• UseState
Setting Up React
Directory Structure
What are React Components..??
Components are independent and reusable chunk of code. They serve the
same purpose as JavaScript functions, but work in isolation and return
HTML.
Stateful Class
Components
Stateless Functional
Components
React
Components
Class v/s Functional Components
Which is better..?
HTML in JS..??
JSX!!
● JSX stands for JavaScript XML.
● Syntax extension of JavaScript. It allows us to directly write HTML in React.
● Compiled using Babel.
● De-reference variables using {}.
● CSS Modules let you use the same CSS class name in different files without
worrying about naming clashes.
● Locally Scoped
CSS Modules
React Hooks
Hooks allow us to "hook" into React features such as state and lifecycle
methods.
There are 3 rules for hooks:
● Hooks can only be called inside React function components.
● Hooks can only be called at the top level of a component.
● Hooks cannot be conditional
The All Round Updater!!
The React useState Hook allows us to track state in a function component.
State generally refers to data or properties that need to be tracking in an
application.
useState()
Kickstart to ReactJS
Pratik Majumdar
@codadept
Day 2 | Part 2
SPA v/s Non-SPA
ReactJS for SPA
● Non-Single Page Application
○ When you go to a new page a request is sent to
the server, the page is retrieved and rendered.
● Single Page Application
○ Loads only single HTML Document file and then
loads different pages via Javascript API and
Logics.
v6
• Pages are created from Components in React
• React Router intercepts any request for any particular page and renders
the needful component accordingly
• Programmatic rendering of Pages
React Router
React Router continued . . .
still v6
• index.html - The single HTML file where all of our components are
rendered programmatically
• When you go to /movies then index.html will be rewritten with
component’s logic
Installing
react-router-dom
pnpm install react-router-dom@6
Let’s code
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import { BrowserRouter } from "react-router-dom";
ReactDOM.render(
<BrowserRouter>
<App />
</BrowserRouter>,
document.getElementById("root")
);
Data Fetching from API
GET: /api/v1/movies
● Front-end applications need to fetch data from
APIs
● Handle different states of the app before, during
and after fetching.
fetching...
• The states to be managed
○ loading
○ data
○ error
Managing states
Different State Management Tools
More hooks?
Redux
Context
API
useState()
App Wide Local
Creating States
states
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
Can use external libraries like, axios too.
Fetching
fetch(url, {
method: "GET" // default, so we can ignore
})
We will use a free online mock API, called JSONPlaceholder to fetch data
https://jsonplaceholder.typicode.com/
Where to write your fetch()?
useEffect() hook?
● fetch() causes side-effects
○ Side-effect, are actions performed with the outside world
○ Unpredictable. For eg. in fetch() result in
■ success
■ Error
● For side-effects: useEffect()
useEffect(() => {
// data fetching here
}, []);
Let’s code
useEffect(() => {
async function getData() {
const response = await fetch(
`https://jsonplaceholder.typicode.com/posts?_limit=10`
)
let actualData = await response.json();
console.log(actualData)
}
getData()
}, [])
Context API
Application-wide state management
● Effectively produce global variables that can be
passed around
● Much better alternative to prop drilling or
passing via props
• Global State (store): The state which needs to be managed application-
wide.
• Producer: Component that provides the state to its children.
• Consumer: Component that consumes and uses the state.
Context API continued . . .
Terminologies
Prop drilling
username
username
username
Using Context API
Each of the Component those who want to Consume
the value (subscriber) can access the username value
without requiring to pass it via props.
Let’s code
function Profile() {
const userDetails =
React.useContext(UserContext);
const setUserDetails =
useContext(UserDispatchContext);
return <h1> {userDetails.username} </h1>;
}
const [userDetails, setUserDetails] =
useState({
username: "John Doe"
});
Context API Demo Code
Resources
RTFM
• React Router
○ https://reactrouter.com/en/main
• Context API
○ https://reactjs.org/docs/context.html
○ https://www.freecodecamp.org/news/react-
context-for-beginners/
Future Read
• React Query
○ https://react-query-v3.tanstack.com/
• React Redux
○ https://react-redux.js.org/
○ https://dev.to/ruppysuppy/redux-vs-context-
api-when-to-use-them-4k3p
• NextJS
○ https://nextjs.org/docs/getting-started
Thank you

GDSC NITS Presents Kickstart into ReactJS

  • 1.
  • 2.
    React is aJavaScript library for building user interfaces. What is ReactJS..?? Is it worth to learn?
  • 3.
    Market needs ReactDevs !! So why not become one..?
  • 4.
    In today’s Session •React Setup • Components and Its types • What’s JSX..? • Using JS in HTML • Importing CSS and CSS Modules • Props • Hooks!! • UseState
  • 5.
  • 6.
  • 7.
    What are ReactComponents..?? Components are independent and reusable chunk of code. They serve the same purpose as JavaScript functions, but work in isolation and return HTML. Stateful Class Components Stateless Functional Components React Components
  • 8.
    Class v/s FunctionalComponents Which is better..?
  • 9.
    HTML in JS..?? JSX!! ●JSX stands for JavaScript XML. ● Syntax extension of JavaScript. It allows us to directly write HTML in React. ● Compiled using Babel. ● De-reference variables using {}.
  • 10.
    ● CSS Moduleslet you use the same CSS class name in different files without worrying about naming clashes. ● Locally Scoped CSS Modules
  • 11.
    React Hooks Hooks allowus to "hook" into React features such as state and lifecycle methods. There are 3 rules for hooks: ● Hooks can only be called inside React function components. ● Hooks can only be called at the top level of a component. ● Hooks cannot be conditional
  • 12.
    The All RoundUpdater!! The React useState Hook allows us to track state in a function component. State generally refers to data or properties that need to be tracking in an application. useState()
  • 13.
    Kickstart to ReactJS PratikMajumdar @codadept Day 2 | Part 2
  • 14.
    SPA v/s Non-SPA ReactJSfor SPA ● Non-Single Page Application ○ When you go to a new page a request is sent to the server, the page is retrieved and rendered. ● Single Page Application ○ Loads only single HTML Document file and then loads different pages via Javascript API and Logics.
  • 15.
    v6 • Pages arecreated from Components in React • React Router intercepts any request for any particular page and renders the needful component accordingly • Programmatic rendering of Pages React Router
  • 16.
    React Router continued. . . still v6 • index.html - The single HTML file where all of our components are rendered programmatically • When you go to /movies then index.html will be rewritten with component’s logic
  • 18.
  • 19.
    Let’s code import Reactfrom 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import { BrowserRouter } from "react-router-dom"; ReactDOM.render( <BrowserRouter> <App /> </BrowserRouter>, document.getElementById("root") );
  • 20.
    Data Fetching fromAPI GET: /api/v1/movies ● Front-end applications need to fetch data from APIs ● Handle different states of the app before, during and after fetching.
  • 21.
    fetching... • The statesto be managed ○ loading ○ data ○ error Managing states
  • 22.
    Different State ManagementTools More hooks? Redux Context API useState() App Wide Local
  • 23.
    Creating States states const [data,setData] = useState(null); const [loading, setLoading] = useState(true); const [error, setError] = useState(null);
  • 24.
    Can use externallibraries like, axios too. Fetching fetch(url, { method: "GET" // default, so we can ignore }) We will use a free online mock API, called JSONPlaceholder to fetch data https://jsonplaceholder.typicode.com/
  • 25.
    Where to writeyour fetch()? useEffect() hook? ● fetch() causes side-effects ○ Side-effect, are actions performed with the outside world ○ Unpredictable. For eg. in fetch() result in ■ success ■ Error ● For side-effects: useEffect() useEffect(() => { // data fetching here }, []);
  • 26.
    Let’s code useEffect(() =>{ async function getData() { const response = await fetch( `https://jsonplaceholder.typicode.com/posts?_limit=10` ) let actualData = await response.json(); console.log(actualData) } getData() }, [])
  • 27.
    Context API Application-wide statemanagement ● Effectively produce global variables that can be passed around ● Much better alternative to prop drilling or passing via props
  • 28.
    • Global State(store): The state which needs to be managed application- wide. • Producer: Component that provides the state to its children. • Consumer: Component that consumes and uses the state. Context API continued . . . Terminologies
  • 29.
  • 30.
    Using Context API Eachof the Component those who want to Consume the value (subscriber) can access the username value without requiring to pass it via props.
  • 31.
    Let’s code function Profile(){ const userDetails = React.useContext(UserContext); const setUserDetails = useContext(UserDispatchContext); return <h1> {userDetails.username} </h1>; } const [userDetails, setUserDetails] = useState({ username: "John Doe" });
  • 32.
  • 33.
    Resources RTFM • React Router ○https://reactrouter.com/en/main • Context API ○ https://reactjs.org/docs/context.html ○ https://www.freecodecamp.org/news/react- context-for-beginners/
  • 34.
    Future Read • ReactQuery ○ https://react-query-v3.tanstack.com/ • React Redux ○ https://react-redux.js.org/ ○ https://dev.to/ruppysuppy/redux-vs-context- api-when-to-use-them-4k3p • NextJS ○ https://nextjs.org/docs/getting-started
  • 35.