ReactJS is a javascript library for building user interfaces. It's not a framework. A library is basically used to solve some common problems, we don't have to write code in Vanilla JS that is pure JS that could be somewhat challenging for people. That means, in order to build complete React applications, you will need to choose the packages and tools on your own. While Angular is usually considered a framework as it provides strong opinions on how your application should be structured.
Javascript library
1. React has reusable components: Code re-use helps make your apps easier to develop and easier to maintain. They also help you implement a consistent look and feel across the whole project.
2. React improves performance due to VDOM.
mkdir
rmdir
rm
mv
mv
cd
ls
pwd
Controller
View
Middleware
Model
cd
pwd
ls
None of Above
cd..
cd ..
Paul O’Shannessy
Jordan Walke
Yuzhi Zheng
Sasha Aickin
Manipulating the real DOM is slow. Manipulating the virtual DOM is much faster.
While trying to update DOM in React, entire real DOM gets updated but virtual DOM doesn't.
Virtual DOM is much slower than real DOM
A virtual DOM object is a representation of a DOM object, like a lightweight copy.
for (var i = 0; i < 5; i++) { setTimeout(function() { console.log(i); }, i * 1000 ); }
012345
55555
12345
54321
let x = 42;
if (true) {
console.log(x);
let x = 1337;
}
42
1337
error
undefined
const KEY = 'coding_ninjas';
if (true) {
const KEY = 'ES6';
}
console.log(KEY);
ES6
coding_ninjas
undefined
var temp= 'hello';
function display(){
console.log(temp);
var temp = 'bye';
};
display();
bye
undefined
hello
null
var array = [1, 2, 3]
const array1 = [4, 5, 6]
var arr1 = array.map(a => a * 2);
array = [...array1, ...arr1]
[1,2,3,4,5,6]
[4,5,6,2,4,6]
[4,5,6,1,2,3]
[2,4,6,4,5,6]
A student is creating a list of electronics items he wants to buy with decreasing priority(highest
priority item at 0 index).
Electronics=['Mobile', 'Watch', 'Kindle'].
But due to college requirements, he wants to keep a certain item as his first priority. Can you add
that item at the start to create a new priority list using the spread operator?
function foo(x, ...y) {
return x * y.length
}
foo(4,1,2,30);
0
12
3
16
Write a program for printing the sum of given numbers.
Input: 1 2 3 4
Output: 10
The spread operator is used to transform an array into its individual elements whereas the rest parameters are used to transform individual elements into an array. Also, the spread operator is used when calling a function whereas the rest parameters are used in the function parameters. - When ... is at the end of function parameters, it’s “rest parameters” and gathers the rest of the list of arguments into an array. - When ... occurs in a function call or alike, it’s called a “spread syntax” and expands an array into a list.
Implicitly returns values
Can be used as a constructor
Is anonymous
Inherits the value of this from its enclosing scope
var title = "A Passage to India";
var author = "E.M. Forster";
var novel = {
title: "Pride and Prejudice",
author: "Jane Austen",
print: function() {
console.log(this.title);
console.log(this.author);
}
}
novel.print();
What will be the output of the above program?
1. Uncaught ReferenceError: this is not defined
Uncaught ReferenceError: this is not defined
2. A Passage to India
E.M. Forster
3. Pride and Prejudice
Jane Austen
2
3
1
4
You have to filter all the students with marks greater than the given grades. Complete the given
function and return the object.
const students = [
{ name: 'Anjali', grade: 96 },
{ name: 'Navdeep', grade: 84 },
{ name: 'Varun', grade: 100 },
{ name: 'Bhavya', grade: 65 },
{ name: 'Shiva', grade: 90 }
];
Suppose you have given an array of numbers and you have to convert all the numbers into their perfect squares. Which of the following array functions are useful to accomplish this?
filter()
map()
reduce()
Remove duplicates from an array using reduce().
Input Format: Given an array as input
Output Format: Return the answer in the form of array after removing duplicates.
Sample Input:
a b c d a b b c d
Sample Output:
a b c d
Choose the correct output.
const scores = [22, 33]
const [math, science = 50, arts = 50, sst] = scores
console.log(math,science,arts,sst);
22 50 50 undefined
22 33 50 undefined
22 33 undefined undefined
undefined 50 50 undefined
const colors = [
'Red',
'Orange',
'Purple',
'Brown',
'Gray',
'Pink'
];
const [primary, ,secondary,...others] = colors;
console.log(primary, secondary, others);
What will be the output?
Red Orange ['Purple', ‘Brown’, ‘Gray’, ‘Pink’]
Red Purple [‘Brown’, ‘Gray’, ‘Pink’]
Red Orange [‘Brown’, ‘Gray’, ‘Pink’]
Purple Orange [‘Brown’, ‘Gray’, ‘Pink’]
Which of the following options correctly represents the output of the following code?
function greet({ name, greeting='hello' }) {
console.log(`${greeting}, ${name}!`)
}
const person = { name: 'Aayushi', dept: 'tech', greeting: 'Welcome'};
greet(person);
Undefined, Aayushi
Welcome, Aayushi
Hello, Aayushi
Aayushi, Welcome
You are given an object which has details of a particular class. Complete the function so that it returns the details of the student at i th index in the form of an array.
Input Format: Given the index (i) of the student whose details should be printed.
Output Format: An array containing name and roll no of the student.
Sample Input:
1
Sample Output
Bhavya
2
Bundles all your javascript files into one
Compiles JSX into Javascript
Runs react local development server
Both B and C
Runs react local development server.
A module bundler
Both of the above
None of the above
0
1
2
Mo limit
True
False
${fetch()}
{fetch()}
{fetch}
${fetch}
{if(loggedIn) {username} else 'Hello World'}
{loggedIn ? username : 'Hello World'}
{if(loggedIn)} ? {username} : 'Hello World'
Conditionals are not allowed in JSX
module
component
package
class
import GIVEN_NAME from ADDRESS
import { NAMED_PARA } from ADDRESS
import GIVEN_NAME, { NAMED_PARA, ... } from ADDRESS
import required {NAMED_PARA } from ADDRESS
JSX editor
Babel
Browser
ReactDOM
React
ReactDOM
Render
DOM
It renders a React element into the DOM in the supplied container and returns a reference to the component.
style={{font-size:10, color:'blue'}}
style={{fontSize:10, color:'blue'}}
style={{font-size:10px, color:'blue'}}
style={fontSize:10', color:'blue'}
onClick={this.foo()}
onClick={this.foo}
onclick={this.foo}
onclick={this.foo()}
A state in React is used to store the property values that belong to a component. it enables a component to keep track of changes between renders
You are given a code to display an image on the page, you have to print “I’m on the image” in the console as soon as you move over the image. So which of the following is a correct event for that?
import React from "react"
function App() {
return (
onmouseover={()=> console.log("Over the Image")}
onMouseOver={()=> console.log("Over the Image")}
onMouseOver=()=> console.log("Over the Image")
onmouseover={()=> console.log("Over the Image")
import React from "react"
function App(){
constructor(){
this.state={
myName: “CN”
}
}
render(){
return (
It should be a class component instead of a functional component
Instead of {this.state.myName} in it should be {myName}
render() statement should not be there.
super() is missing from the constructor
be re-rendered
be created again from scratch
do nothing , you have to call the render method to render the component again
None of above
render(){
let code = ["Java","ES6","Ruby"]
return (
{item}
)}Displays Nothing
Displays the list of code in the array
Error. Cannot use direct JavaScript code in JSX
Error. Should be replaced with a for..loop for correct output
style={{background-color:'yellow',color:’green’}}
style={background-color:'yellow',color:’green’}
style={backgroundColor:'yellow',color:’green’}
style={{backgroundColor:'yellow',color:’green’}}
Repetitive output appears on the screen
Stack overflow error
Duplicate key error
Nothing happens
handleClick = () => {
this.setState({ number: 2 }, () => console.log(this.state.number));
this.setState({ number: 3 }, () => console.log(this.state.number));
}
1 2
3 3
2 3
3
handleClick = () => {
this.setState(
prevState => {
return {
number: prevState.number + 2
};
}
);
this.setState(
prevState => {
return {
number: prevState.number + 3
};
}
);
};
3
6
4
1
Synchronous in nature
Asynchronous in nature
Are asynchronous but can be made synchronous when required
None of above
Directly updating the state will give you error.
It won’t re render the component.
It will not change the state.
It goes into infinite loop
The callback function is invoked when setState is finished and the component gets rendered. Since setState() is asynchronous the callback function is used for any post action.
unique in the DOM
unique among the siblings only
not required
None of above
be changed inside the component
not be changed in the component
be changed using this.setProps
None of above
Props are used to pass information from one component to another.
Anything can be passed as a prop in React including event handlers
React props can be accessed as an object or destructured
Props cannot be directly updated.
State & Component
State & Props
Components & Functions
Props & Components
We cannot use state for defining default values in a component.
States can be modified by using setState() and props can be modified using setProps()
Props are immutable and States are mutable.
States can only be defined in the component itself.
this.name
this.props.name
this.props
props.name
this.props.name
props.name
this.name
this.props
filter()
filter
Clean syntax and less code
Scope safety
Difficult to implement
To avoid binding `this` to methods
Using the reduce array method
Using the Array.map() method
Using the
With a for/while loop
const cartItem = {
itemName: 'Apples',
qty: 6,
price: 10
};
const { qty=1, price } = cartItem;
console.log("Total price of", cartItem.itemName , 'is', qty*price);
Total price of Apples is 60
Local Storage
props
state
Redux
willComponentUpdate
shouldComponentUpdate
componentDidUpdate
componentDidMount
shouldComponentUpdate
componentWillUnmount
componentWillMount
componentDidMount
The next props
The current props
The next state
The current state
Document within same collection should have same field
A Document can contain another Collection
A Collection can contain another Collection
Names of Documents within a collection can be same
componentDidUnmount
componentWillUnmount
shouldComponentUnmount
componentDidCatch
db.collection(‘cities’).doc(‘delhi’).delete(‘capital’)
docRef.update({ capital: firebase.firestore.FieldValue.delete() });
docRef.delete(‘capital’)
docRef.delete({ capital:firebase.firestore.delete() }
SF, LA,DC
DC
SF
LA
citiesRef.where("state", ">=", "CA").where("population", ">", 100000);
citiesRef.where("state", "==", "CA").where("population", ">", 1000000);
studentsRef.where("age", "!=", "30")
firebase.firestore().doc(documentID)
firebase.firestore().collection(collectionName).doc(documentID)
firebase.collection(collectionName).doc(documentID)
firebase.firestore().collection(collectionName).get().then((documentID) => {})
firebase.collection().get()
firebase.firestore().get()
firebase.firestore().collection().get()
firebase.firestore().collection(‘all’).get()
useEffect( ( ) => { })
useEffect( ( ) => { }, [ ] )
useEffect( ( ) => { }, { } )
useEffect( ( ) => { }, null )
Class Button {
render () {
const [text, setText] = useState(‘’);
return
}
}
Can’t use hook inside the render function
Can’t use hooks inside a class
All is good, it will work
Have to wrap
False
True
npx create react-app foldername
npx create-react-app foldername
npm create-react-app foldername
npm create react-app foldername
import {BrowserRouter} from react-router-dom
import {BrowserRouter} from “react-router-dom”
import BrowserRouter from react-router-dom
import “BrowserRouter” from “react-router-dom”
export “App, Navbar, Home, CreatePost, PostDetail”;
export {App, Navbar, Home, CreatePost, PostDetail};
export {App}, {Navbar}, {Home}, {CreatePost}, {PostDetail};
export App, Navbar, Home, CreatePost, PostDetail;
Switch
Router
Link
Route
stopDefault()
preventDefault()
preventEvent()
stopEvent()
False
True
Relational Database
NoSQL Database
Realtime Database
Cloud-Hosted Database
onFailureListener()
onSnapshot()
onUpdate()
onSuccessListener()
useCallback
useParams
useContext
useRef
firebase build
firebase deploy
firebase init
firebase start
apply to all the components
apply to the component where imported
apply to 2 components
apply to only nested components
styled.anchor`color: white`
styled.a`color: white`
styled.`color: white`
styled.a`{color: white}`
False
True
styled.button`background: props => props.color`
styled.button`background: ${props => props.color}`
styled.button`background: props.color`
styled.button`(props) => background: props.color`
It supports browser state styles
It supports Media queries
Keyframes animation helper
Automatic vendor prefixing
Div
StyleRoot
Fragment
Root
Scope.css
Scope.module.css
module.Scope.css
ScopeModule.css
box-container
BoxContainer
boxContainer
boxcontainer
/providers
/utils
/public
/api
JSON.parse(), JSON.stringify()
JSON.stringify(), JSON.parse()
JSON.stringify, JSON.display()
JSON.display(), JSON.parse()
In which all class names and animation names are scoped locally by default.
In which all class names and animation names are scoped globally by default.
In which class names are dynamically generated, unique, and mapped to the correct styles.
Which prevents name conflicts and lets you use the same css class name in different files.
Props Validator
Prop Types
Props Data
None of the above
POST - Create
REMOVE - Delete
GET - Read
PATCH/POST - Update
API keys
Authentication tokens
API tokens
None
setItem()
getItem()
removeItem()
key()
A callback is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of action.
Pending: before the event happens
Rejected: when the promise does not return the correct result
Settled/Resolved: after the event happens
Fulfilled: when the promise returns the correct result.
BrowserRouter
Switch
Router
Route
stateful
Stateless
False
True
Anchor
Link
Route
Route
Cookies
JWT
Session
JSON objects
const theme = React.createContext();
What would the following statements log after the execution of this statement?
const {primary} = React.useContext(theme);
console.log(theme);
null
It will give an error
undefined
0
Redux store
Local storage
Memory
React state
localStorage.setItem(key,value)
localStorage.removeItem(key,value)
localStorage.getItem(key)
All are correct
localStorage
React state
memory
Redux store
because the user is not logged in.
because the Authentication token is not updated.
because response.success is returning false.
because setEditMode is returning false.
Public Route
Private Route
Restricted Route
None of these
action
push
replace
go
useToasts
addToast
updateToast
removeToast
Settings Page
Log In page
Sign Up Page
Profile Page
uselocation
useLocation
const user = {
id: 120,
name: "Aayushi",
email: "aayushi@abc.com",
friends: [123, 124, 125]
};
function addFriend(friend) {
user.friends=[...user.friends, friend]
return;
}
addFriend(121);
console.log(user.friends);
[121, 123, 124, 125]
[123, 124, 125, 121]
[123, 124, 125]
[124, 125, 121]
No. of likes were constant.
Newly added post was not visible as soon as it was added.
Toast notification did not appear.
Unable to see the post content.
Context provides a way to pass data through the component tree without having to pass props down manually at every level. Context is designed to share data that can be considered “global” for a tree For example, authenticated user, locale preference, UI theme need to be accessed in the application by many components.
useContext
createContext
context.provider
context.consumer
Changes are made with pure functions
Non-Predictable
State is read-only
Single source of truth
● Always Predictable: The state in redux is always predictable as a state and is immutable and can’t be changed. If the same state and actions are passed to redux always the same output comes because reducers are pure functions.
● Easily Maintainable: Redux is strict towards organising its code so it is very easy for someone who has knowledge of redux to understand the application. Hence this is why redux is easy to maintain.
You usually need redux when your app has grown to a level where it has become difficult to maintain the app state and you are looking to make it easy and simple.
Actions
Reducer
Store
Dispatcher
Framework
Library
Programming Language
Redux is a small standalone JS library. It is a predictable state container for JavaScript apps. Redux is mostly used for application state management. In a nutshell, Redux maintains the status of the entire application in a single unchanged state tree (object), which cannot be changed directly. When anything changes, a new object is created (using actions and reducers).
Action
State tree
Reducers
Store
Action
State tree
Reducers
Store
Action
State tree
Reducers
Store
Action
State tree
Reducers
Store
Changing a deep copy of input argument
Changing a shallow copy of input argument
Modifying variable whose scope is function itself
Same Output for same input
undefined
0
function/p>
True
var x = 1;
const a = () => {
var x = 2;
return x*100;
}
No
Yes ,, It is a pure function because it doesnt rely on any global variables, the return statement uses the x from the local scope
const reducer = (state, action) => state
What will be the result of creating a redux store from the following reducer like this?
const store = createStore(reducer)
console.log(store.getState())
Null
Undefined
0
NaN
An action
A state
A value of the state that requires an action
A store
UI -> reducer -> action -> store
UI -> action -> reducer -> store
UI -> action -> store -> reducer
UI -> reducer -> store -> action
The current state
The dispatched action
The next state
A function to unsubscribe to the store
False
True
combineReducers({ add, subtract })
combineReducers({ add: addReducer, subtract: subtractReducer })
combineReducers({ add: subtract })
combineReducers()
to make ajax requests only
to write action creators that return a function instead of an action
to log different actions that are dispatched
None of the above
Nothing
A function
an action
The current state
False
True
function
nothing
action
state
A reducer
dispatch
Store
The next() in the last middleware in undefined
const f = () => () => () => fetch
Is this call valid?
f()()()(API_URL)
No
Yes
Components that does not have any state
A function that takes a component as the argument and returns another component
A function that returns a new component
None of the above
Helps to build reusable components
Connects a react component to a redux store
Connects a react component to another component
None of the above
react
react-redux
redux-thunk
0
1
2
3
An object
A function
Another component
A context provider
A function
A component
An object
The store
To add more modularity to the code
To pass the store into props of the actual component
To write non visual re usable logic
To connect different components
False
True