React Flashcards

1
Q

Why React?

A

Fast
Extensive library
Active community

Compositional/Modular
Declarative
Unidirectional Dataflow
just javascript

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is a simple server we can setup for development

A

npm i -g live-server

live-server public

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is Babel?

A

Javascript compiler

Compiles jsx into es5

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Why can if statements not be used in templates but a ternary can?

A

Because a ternary is an expression while if statements is a statement or controll structure. ONLY expressions can be used in jsx.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What are 3 things that are ignored by jsx?

A

undefined, null and booleans

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How to add conditional logic to jsx?

A
  1. Ternary expressions
  2. Logical && operator
  3. Logical || operator
  4. Define a function outside of the template that handles conditional logic and then call the funciton in jsx
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Difference between var, let, const.

A

Var can be redefined and reassigned.

let cannot be redefined but can be reassigned

const cannot be redefined or reassigned.

let and const are block scoped, whereas var is excecution context or function scoped. Var variables are hoisted, whereas const and let are not.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What needs to happen before the browser can read jsx?

A

The jsx code or file needs to be transpiled in javascript. This is done through babel.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

difference between arrow functions and function declarations and expressions

A

Arrow functions are anonymous

arrow expression Syntax is more concise, do not need to explicitly return a value when declared on the same line

Arrow funcitons does not bind it’s own this value. It uses it’s parents this value, If you want to use an objects this value, use function declarations, if you want to use an object’s parents this value then use arrow function.

arguments objects are not bound with arrow functions, which means you cannot access the arguments object within the arrow funcitons

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What needs to be done for a es5 function to use it’s parent’s this value

A

const that = this

function(){
that.value
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

How are the attributes in jsx different from html attributes

A

class = className

use camelCase instead of hyphens

form-target = formTarget

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

JSX does not have built in data binding, what does this mean?

A

It meas that whenever a value in a template is updated the template has to be re-rendered in order for it to be updated.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What is data-binding?

A

Keeping state in sync with views

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

How to turn a value into a boolean

A

!!value

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

How to turn a value into a boolean

A

return !!value

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

In order to create a component what must an es6 class extend?

A

React.component

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

What is the one method tha t must be defined in a React componenent class?

A

render(){
return (
)

}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

How to get a value from the input field

A

add name=”someName” attribute to the input field

in the event handler get the value with:

e.target.elements.someName.value

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

how to bind a method in a class component

A
//in constructor
this.methodName = this.methodName.bind(this)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

How to set default state in a component

A
//in constructor
this.state = {
        key:value
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

How to change or update state?

A
this.setState((prevState)=>{
         return {
               key: prevState.value + 1
         }
})
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

What is the difference between a class based component and a stateless functional component?

A

SFC’s are just functions that return jsx. SFC’s can acces props but cannot contain states.

SFC’s are a lot faster than class based components and should therefore be used instead of class based components whenever possible?

Lifecycle methods can be added to class based components but not SFC’s

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

How to add default props to a component?

A

Header.defaultProps = {
key:’some value’
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

LIfecycle of a component

A
  1. coponentWillMount -executes before initial rendering
  2. componentDidMount - imediately after the initial rendering
  3. componentWillRecieveProps - When component recieves new props
  4. shouldComponentUpdate -before rendering, after receiving new props or state
  5. componentWillUpdate -after shouldComponentUpdate returns true
  6. componentDidUpdate - after rerender
  7. .componentWillUnmount -just before removing component from Dom
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

Which babel dependencies needs to be installed?

A
@babel/cli
@babel/core
@babel/preset-env
@babel/preset-react
babel-loader
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

What is webpack

A

At its core, webpack is a static module bundler for modern JavaScript applications. When webpack processes your application, it internally builds a dependency graph which maps every module your project needs and generates one or more bundles.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

Webpack setup

A

install webpack and webpack cli

create a webpack.config.js file

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

webpack configuration

A

//webpack.config.js file

const path = require(‘path’)

module.exports = {
mode:’development’,
entry:’./src/index.js’,
output:{
path: path.join(__dirname,”public”),
filename:’bundle.js’,
},
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

How to configure webpack to work with babel?

A
  1. install babel dependencies
    - @babel\cli
    - @babel\core
    - @babel\preset-env
    - @babel\preset-react
    - babel-loader
  2. Add module to weppack.config.js file

module:{
rules:[{
loader:’babel-loader’,
test:/.js$/,
exclude:/node_modules/
}]
},

  1. Setup .babelrc file and configure presets
{
  "presets":[
    "@babel/env",
    "@babel/react"
  ]
}
  1. update scripts in package.json

“build”:”webpack”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
30
Q

How to setup dev server with webpack

A
  1. install webpack-dev-server
  2. add devServer to wepack.config.js file

devServer:{
contentBase: path.join(__dirname,’public’)
}

  1. create Script in package.json

“dev-server”:”webpack-dev-server”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
Q

How to access children of a component

A

props.children

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
32
Q

Difference between server-side routing and client-side routing?

A

Server-side routing makes an http request to the server which then renders a new page to the browser.

client-side routing uses the html5 history api to watch for url changes and then finds associated componenent and then runs the associated javascript function rendering a new page.

server-side is faster than client-side

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
33
Q

How to setup webpack to process scss and css files?

A

install:

  • css-loader
  • sass-loader
  • style-loader
  • node-sass
  • normalize.css

add the following to webpack.config.js models

{
            test:/\.s?css$/,
            use:[
                'style-loader',
                'css-loader',
                'sass-loader'
            ],
    }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
34
Q

How to add a favicon to html page?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
35
Q

When using webpack, what needs to be added to the html file?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
36
Q

What is React Fiber ?

A

Fiber is the new reconciliation engine in React 16. Its main goal is to enable incremental rendering of the virtual DOM.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
37
Q

What is the ‘virtual Dom”?

A

The virtual DOM (VDOM) is a programming concept where an ideal, or “virtual”, representation of a UI is kept in memory and synced with the “real” DOM by a library such as ReactDOM. This process is called reconciliation.

  • its a JSON object that is a representation of the DOM
  • Extremely fast compared to the DOM
  • Can produce 200,000 virtual DOM nodes a second
  • Created copletely from scratch on every setState or dispatch
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
38
Q

Explain reconciliation

A

The process of making the DOM match the virtual DOM

React uses a diffing algorithm to compare the DOM to the virtual DOM and when a node is foudn to be different it will re-render that node and the entire subtree,

instead of re-rendering the entire DOM only the nodes that have changed are rerendered

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
39
Q

What is the architecture of the React library?

A

MVC

model -components

View - the ui

controller - user input

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
40
Q

What data structure does the REACT virtual DOM use?

A

Tree structure

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
41
Q

Explain the diffing algorithim?

A

Once react creates anew virtual DOM and diffsit vs the old one, it creates a list of minimum possible changes to the browser DOM

Once it copletes its list, it will fire off all of the changes one after the other as fast as possible

Accomplishes this in one continous write cycle without any reflow until the end

Reflow is the process that the browser performs to recalculate the positions, geometries and colors of elements on the page

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
42
Q

Why use Redux?

A

React state management is simplistic and becomes problematic when you have multiple component trees with no single parent component. Redux makes it easier to manage state between trees and to share states between components

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
43
Q

What is Redux?

A

A Global State Container

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
44
Q

Which redux method runs everytime a change is made to the store and can be used to track changes?

A
const unsubscribe = store.subscribe(()=>{
    console.log(store.getState().count)
})

store.dispatch({
type:’INCREMENT’
})

unsubscribe();

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
45
Q

When destructuring an object, how can one set defualts in the event that the property does not exist within the object?

A
const person = {
         name: "david",
         age: 21
}

const {name, age = ‘unknown’} = person

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
46
Q

When destructuring an object, how can one change the property name?

A
const person = {
         name: "david",
         age: 21
}

const {name: firstName, age: biologicalAge} = person

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
47
Q

How to destructure an array?

A

const address = [‘102 Palian Street’, ‘Oanang’,’Krabi’,’95000’]

const [street,city,state,zip] = address

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
48
Q

2 attributes of reducers

A
  1. reducers are pure functions

2. Never change state or actions

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
49
Q

When updating state arrays in react or redux, why should we use .concat or the spread opperator instead of .push?

A

Because push will modify the original array, whereas .concat returns a new one

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
50
Q

which babel plugin enables the use of object spread opperators?

A

babel-transform-object-rest-spread

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
51
Q

What are higher order components?

A

a higher-order component is a function that takes a component and returns a new component.

const EnhancedComponent = higherOrderComponent(WrappedComponent);

Whereas a component transforms props into UI, a higher-order component transforms a component into another component.

a HOC doesn’t modify the input component, nor does it use inheritance to copy its behavior. Rather, a HOC composes the original component by wrapping it in a container component. A HOC is a pure function with zero side-effects.

And that’s it! The wrapped component receives all the props of the container, along with a new prop, data, which it uses to render its output.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
52
Q

What are the main components of Redux?

A

Store
Reducers
Action Generators
Selectors

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
53
Q

How to create a Redux store?

A

import {createStore} from ‘redux’

const store = createStore(countReducer)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
54
Q

How to create a redux reducer?

A
const countReducer = (state={count:0},action)=>{
    switch(action.type){
        case 'INCREMENT':
            return {
                count:state.count + action.incrementBy
            };
        case 'DECREMENT':
            return {
                count:state.count - action.decrementBy
            };
        case 'SET':
            return {
                count:action.count
            }
        case 'RESET':
            return {
                count:0
            };
        default:
            return state;
    }
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
55
Q

How to create a redux action generator?

A
const incrementCount = (value=1) => {
    return {
        type: 'INCREMENT',
        incrementBy: typeof value === 'number' ? value : 1
    }
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
56
Q

How to perform an action on a redux store?

A

Use the dispatch method, which takes in an action generator as an argument.

const expenseOne = store.dispatch(addExpense({description:’Rent’,amount:100, createdAt:3200}))

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
57
Q

How to create a selector that filters the data in a redux store?

A
const getVisibleExpenses = (expenses, {text,sortBy,startDate,endDate}) =>{
    return expenses.filter((expense)=>{
        const startDateMatch = typeof startDate !== 'number' || expense.createdAt >= startDate;
        const endDateMatch = typeof endDate !== 'number' || expense.createdAt <= endDate;
        const textMatch = typeof text !== 'string' || expense.description.toLowerCase().includes(text.toLowerCase())
        return startDateMatch &amp;&amp; endDateMatch &amp;&amp; textMatch;
    }).sort((a,b)=>{
        if(sortBy === 'date') {
            return a.createdAt < b.createdAt ? 1:-1;
        }else{
            return a.amount < b.amount ? 1:-1;
        }
    });
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
58
Q

How to combine redux reducers into one store?

A

import {createStore, combineReducers} from ‘redux’

const store = createStore(
    combineReducers({
        expenses: expensesReducer,
        filters:filtersReducer,
    })
);
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
59
Q

How to create a higher order component?

A
const Info = (props)=>{
    return (
        <div>
            <h1>Info</h1>
            <p>The info is: {props.info}</p>
        </div>
    )
}

const requireAuthentication = (WrappedComponent) =>{
return (props) =>{
return (
<div>
{props.authenticated === true ? <h1>Authenticated</h1>:<h1>Not Authorized</h1>}
{props.authenticated === true && }
</div>
)

} }

const AuthInfo = requireAuthentication(Info)

ReactDOM.render(,document.getElementById(‘root’))

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
60
Q

What library can be used instead of working with the Date() api?

A

yarn add moment

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
61
Q

How to get a timestamp from the moment library?

A
const now = moment()
now.format()
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
62
Q

steps to creating a production build

A
  1. Update webpack.config.js file
    - set mode to production
    - set devtools to ‘source-map’ if in production otherwise set it to ‘inline-source-map’
  2. set build script
    - “webpack -p –env production”

3 minify css
- yarn add mini-css-extract-plugin

4.Setup Express server

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
63
Q

setup redux to work with react

A
  1. setup store with reducers and export “configureStore”

2.in app.js
import {Provider} from ‘react-readux’
import configureStore from ‘configureStore’

//create store
const store = configureStore();

//pass store into Provider and wrap the App in it

const jsx = (

)

ReactDOM.render(jsx, document.getElementById(‘root’));

3.Access the store using {connect} in components to mapStateToProps and export a higher order function

const mapStateToProps = (state)=>{
    const visibleExpenses = selectExpenses(state.expenses, state.filters)
    return{
        expenseCount:visibleExpenses.length,
        expensesTotal:selectExpensesTotal(visibleExpenses)
    }

};

export default connect(mapStateToProps)(ExpenseSummary);

  1. update state from componenents by accessing props.dispatch and dispatching the relevant action generators
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
64
Q

What are webHooks?

A

Hooks are functions that let you “hook into” React state and lifecycle features from functional components. Hooks don’t work inside classes — they let you use React without classes .They let you use state and other React features without writing a class.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
65
Q

What does calling useState do?

A

It declares a “state variable”. This is a way to “preserve” some values between the function calls — useState is a new way to use the exact same capabilities that this.state provides in a class. Normally, variables “disappear” when the function exits but state variables are preserved by React.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
66
Q

What do we pass to useState as an argument?

A

The only argument to the useState() Hook is the initial state. Unlike with classes, the state doesn’t have to be an object. We can keep a number or a string if that’s all we need. In our example, we just want a number for how many times the user clicked, so pass 0 as initial state for our variable. (If we wanted to store two different values in state, we would call useState() twice.)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
67
Q

What does useState return?

A

It returns an array of 2 values: the current state and a function that updates it. This is why we write const [count, setCount] = useState(0). This is similar to this.state.count and this.setState in a class, except you get them in a pair.

We declare a state variable called count, and set it to 0. React will remember its current value between re-renders, and provide the most recent one to our function. If we want to update the current count, we can call setCount.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
68
Q

Different Webhooks

A
useState()
useReducer()
useEffect()
useLayoutEffect()
useReg()
useCallback()
useContext()
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
69
Q

What does Effect Hooks do?

A

The Effect Hook lets you perform side effects in function components. It is similar to componentDidMount and componentDidUpdate lifecycles. React lifecycle methods are not allowed within a functional component, so instead we use Effect hooks.

Effect hooks are also used as cleanup functions that remove subscriptions before component is removed in order to save memory.

70
Q

When does the useState hook bail out of rerendering?

A

If you update a State Hook to the same value as the current state, React will bail out without rendering the children or firing effects. (React uses the Object.is comparison algorithm.)

71
Q

When do effect hooks run?

A

effects run after every completed render(componentDidMount) and when state has updated(stateDidUpdate), but you can choose to fire them only when certain values have changed.

72
Q

How to run useEffect conditionally?

A

By adding an array of dependencies as a second argument.

useEffect(
  () => {
    const subscription = props.source.subscribe();
    return () => {
      subscription.unsubscribe();
    };
  },
  [props.source],
);
73
Q

How is useState() different from setState?

A

setState is used in class components, while useState is used in functional components.

useState does not need to be called with an object.

You can call useState as many times as you need to within a given component for all the different things you want to track

When updating the state, unlike setState, useState completetely replaces the previous state, instead of merging the differences like setState does.

74
Q

What are some uses for useEffect()

A

To keep state and UI in sync

To read and save data to database

To cleanup data and remove subscriptions or event listeners before component unmounts

75
Q

Difference between useEffect() and lifecycle methods like componentDidMount()?

A

unlike lifecycle methods which can only defined once, multiple useEffect statements can be defined in a functional component

76
Q

How to get useEffect() to run only once?

A

pass in an empty array as the second argument

77
Q

how to get useEffect() to run conditionally?

A

pass in an array of conditions as the second argument

78
Q

How to run useEffect() just before a component is removed to cleanup code?

A

inside the callback function return another function which runs the cleanup code

79
Q

Difference between redux and useReducer()

A

useReducer allows for complex state management within a component. Redux allows for the sharing of state between components. Redux also requires the setup of a provider and the use of connect to map state to props in components that uses redux

80
Q

How to create a context hook?

A

//in seperate file

import React from ‘react’

const SomeContext = React.createContext()

export default SomeContext

//in app file

import SomeContext form “../context/somecontext”

….
return (

)

//in component

import React, {useContext} from ‘React’
import SomeContext from ‘../context/SomeContext’

const component = () => {
         const sharedValue = useContext(SomeContext)

}

81
Q

What are fragments?

A

Fragments let you group a list of children without adding extra nodes to the DOM. There is also a new short syntax for declaring them.

82
Q

When using useState it is usually better to use separate statements for each item being managed, except when…

A

two or more data items change together like x,y coordinates. In that case you would use an object that contains both x, y items and update them together.

83
Q

What does React.memo() do?

A

memo will compare props and only rerender a component once a prop has changed or updated

In other words memo prevents the rerender of a component if it’s props have not changed

84
Q

What does useCallback do?

A

useCallback will return a memoized version of the callback that only changes if one of the inputs has changed. This is useful when passing callbacks to optimized child components that rely on reference equality to prevent unnecessary renders (e.g. shouldComponentUpdate).

85
Q

What is the most common use of the useCallback hook?

A

to prevent the rerender of a child component to which a callback function has been passed.

A function within a component is recreated each time that component rerenders, thus if that function has been passed to a child component via a prop, the child component will also rerender because the prop has been updated with the “new” function.

To prevent this from happening, the function can be defined with the useCallback function, which will prevent that function from being recreated each time the component rerenders.

86
Q

What is the class based equivalent to React.memo()?

A

Extend PureComponent class or define a custom implementation of shouldComponentUpdate() method if you need memoization for class-based components.

87
Q

What is the useRef() hook used for?

A

Used when we need a reference to a variable which will persist across the entire lifetime of the component instance, and that wont be re-initialized when component rerenders.

Refs also provide a way to access DOM nodes or React elements created in the render method.

88
Q

What is the difference between useRef and createRef

A

createRef will return a new ref on every render while useRef will return the same ref each time.

unlike createRef, useRef can hold a value in its .current property and it can persist after the component rerenders. Therefore, useRef is useful more than just managing the component ref

89
Q

How to access a dom element by using createRef

A

const x = React.createRef()

function focusInput(){

x.current.focus() //accesses the dom element.

}

90
Q

Difference between imperitive and declarative programming

A

“Imperative programming is like how you do something, and declarative programming is more like what you do.”

Imperative programming: telling the “machine” how to do something, and as a result what you want to happen will happen.

Declarative programming: telling the “machine”1 what you would like to happen, and let the computer figure out how to do it.

React is declarative, whereas JQuery is Imperitive

91
Q

Two-way data-binding and it’s problems

A

Front-end frameworks like Angular and Ember make use of two-way data bindings. In two-way data binding, the data is kept in sync throughout the app no matter where it is updated. If a model changes the data, then the data updates in the view. Alternatively, if the user changes the data in the view, then the data is updated in the model. Two-way data binding sounds really powerful, but it can make the application harder to reason about and know where the data is actually being updated.

92
Q

Uni-directional data flow within React

A

Unidirectional data flow, means that data flows from parent to child only, which makes it easier to keep track of data changes in the app.

The data lives in the parent component and is passed down to the child component. Even though the data lives in the parent component, both the parent and the child components can use the data. However, if the data must be updated, then only the parent component should perform the update. If the child component needs to make a change to the data, then it would send the updated data to the parent component where the change will actually be made. Once the change is made in the parent component, the child component will be passed the data (that has just been updated!).

93
Q

What is the difference between REACT and other frameworks, when it comes to building the user interface?

A

REACT doesn’t use strings, but rather builds the UI out of simple javascript objects.

React.createElement( /* type /, / props /, / content */ );

94
Q

What is the relationship between React.createElement and the dom?

A

React.createElement doesn’t create real dom nodes, rather it creates an object that represents a dom node. The real dom node is only created when ReactDOM.render() is called.

95
Q

How does the Single Responsibillity principle apply to components?

A

a component should ideally only do one thing. If it ends up growing, it should be decomposed into smaller subcomponents.

96
Q

Three questions for distinguishing between State and props

A

Is it passed in from a parent via props? If so, it probably isn’t state.

Does it remain unchanged over time? If so, it probably isn’t state.

Can you compute it based on any other state or props in your component? If so, it isn’t state.

97
Q

Which component should own the state?

A

For each piece of state in your application:

Identify every component that renders something based on that state.

Find a common owner component (a single component above all the components that need the state in the hierarchy).

Either the common owner or another component higher up in the hierarchy should own the state.

If you can’t find a component where it makes sense to own the state, create a new component solely for holding the state and add it somewhere in the hierarchy above the common owner component.

98
Q

Describe the process of component thinking

A
  1. Break the UI into a component hierarchy (atomic design)
  2. Build a static version in REACT
  3. Identify The Minimal (but complete) Representation Of UI State
  4. Identify where the state should live
  5. Add inverse data flow
99
Q

What is the “Single Responsibility Principle” and how does it apply to REACT components?

A

SRP states that each software module should have one and only one reason to change.

This is more than just saying that each component or module should do only one thing, but rather it has to do with separation of concerns, in that we should gather together the things that change for the same reasons into a module or component and separate those things that change for different reasons.

When a component does only one thing and has only one reason to change, it makes it less likely that we will break our code in other parts of our program when we update that module or component.

100
Q

Why is the process of rendering decoupled from the content being rendered?

A

Decoupling makes it possible to render on different devices: Servers, Dom, VR environments

101
Q

What are components

A

Conceptually, components are like JavaScript functions. They accept arbitrary inputs (called “props”) and return React elements describing what should appear on the screen.

102
Q

How to see the props being passed into a component?

A

console.log(“Props”, this.props);

103
Q

Biggest difference between state and props?

A

props refer to attributes from parent components. In the end, props represent “read-only” data that are immutable.

A component’s state, on the other hand, represents mutable data that ultimately affects what is rendered on the page. State is managed internally by the component itself and is meant to change over time, commonly due to user input (e.g., clicking on a button on the page).

104
Q

Why should we not use props to defining intial state?

A

When defining a component’s initial state, avoid initializing that state with props. This is an error-prone anti-pattern, since state will only be initialized with props when the component is first created.

this.state = {
user: props.user
}
In the above example, if props are ever updated, the current state will not change unless the component is “refreshed.” Using props to produce a component’s initial state also leads to duplication of data, deviating from a dependable “source of truth.”

105
Q

What is reconcilliation?

A

process of determining what has changed in the previous and new outputs

106
Q

What arguments can be passed into setState()?

A
  1. A function that takes prevState as an argument (used when updating a state)
  2. An object (used when replacing a state)
107
Q

What is propTypes?

A

PropTypes is a package that lets us define the data type we want to see right from the get-go and warn us during development if the prop that’s passed to the component doesn’t match what is expected.

npm install prop-types

//add propTypes to components

ListContacts.propTypes={
contacts:PropTypes.array.isRequired,
onDeleteContact:PropTypes.func.isRequired
}

108
Q

Difference between controlled and uncontrolled components?

A

In a controlled component, form data is handled by a React component. The alternative is uncontrolled components, where form data is handled by the DOM itself.

109
Q

How should forms be handled in REACT?

A

Controlled component

set the form value = this.state.someValue and then set the onChange eventhandler to a method that updates the state with the event.target.value.

110
Q

What is the setState signiture?

A

setState(updater, [callback]);

An updater

Either an object literal OR a function.
An optional callback

setState() is asynchronous.
The callback is called when the Component state has actually updated.

111
Q

should state be modified directly, using this.state = newState?

A

No, modifying state directly will not trigger a re-render of the components

Use setState() instead

112
Q

is setState synchronous or Asynchronous?

A

Asynchronous.

Do not call setState on one line and assume the state has already changed on the next line.

setState() is a request to update state, rather than an immediate command to update state. setState() does not always immediately update the component.

113
Q

setState() doesn’t change or update state immediately. How can we ensure that code runs only after the state has been updated?

A
  1. Using componentDidUpdate

componentDidUpdate(prevProps, prevState) {
console.log(this.state.orders); // Prints out: 1
}

  1. a setState callback (setState(updater, callback)) guarantees your code will execute after the state update has been applied.

example:

 this.setState(
  {
    orders: 1
  },
  () => {
    //code to execute
  }
);
114
Q

Why should this.state not be used to update or increment existing state?

A

because setState is Async. and state is not changed immediately. instead, use prevState

this.setState((prevState, props) => ({
orders: prevState.orders + props.increment
}));

115
Q

Why should we not perform mulitple setState() calls in the same render cycle?

A

Because, subsequent calls will overide values from previous calls in the same cycle

// It is equivalent of an Object.assign, which performs a shallow merge
// The orders will only be incremented once
Object.assign(
  previousState,
  {orders: state.orders + 1},
  {orders: state.orders + 1},
  {orders: state.orders + 1},
  ...
)

Solution: Use the updater function form to queue state updates

By passing updater a function, the updates will be queued and later executed in the order they were called.

this. setState(prevState => ({ orders: prevState.orders + 1 }));
this. setState(prevState => ({ orders: prevState.orders + 1 }));
this. setState(prevState => ({ orders: prevState.orders + 1 }));

116
Q

What are anti-patterns

A

Anti-patterns are certain patterns in software development that are considered bad programming practices.

117
Q

Why should we bind custom functions in the constructor instead of when we pass it as a prop to another component?

A

Since .bind() creates a new function each time it is run, this method would lead to a new function being created every time the render function executes. This has some performance implications. However, in a small app it may not be noticeable. As the app grows large, the difference will start to materialise.

118
Q

What is meant by side-effects in React, and which method should be free of side-effects?

A

“side effect” is anything that affects something outside the scope of the function being executed. These can be, say, a network request, which has your code communicating with a third party (and thus making the request, causing logs to be recorded, caches to be saved or updated, all sorts of effects that are outside the function.

The render method should have no side-effects

119
Q

In what order are lifecycle methods called when a component mounts?

A

constructor()
static getDerivedStateFromProps()
render()
componentDidMount()

120
Q

Which three lifecycle methods are now considered legacy code and unsafe?

A

componentWillMount()
componentWillUpdate()
componentWillReceiveProps()

121
Q

In what order are lifecycle methods called when a components updates?

A
static getDerivedStateFromProps()
shouldComponentUpdate()
render()
getSnapshotBeforeUpdate()
componentDidUpdate()
122
Q

In what order are lifecycle methods called when a components are removed?

A

componentWillUnmount()

123
Q

Which lifecycle method removes a component from the DOM?

A

componentWillUnmount()

124
Q

Which lifecycle method prevents a component from re-rendering?

A

render() will not be invoked if shouldComponentUpdate() returns false.

125
Q

Which lifecycle methods are best for handling subscriptions?

A

componentDidMount() for creating subscriptions

componentWillUnmount() for removing or closing subscriptions

126
Q

What happens when setState() is called within the componentDidMount() method.

A

It will trigger an extra rendering, but it will happen before the browser updates the screen. This guarantees that even though the render() will be called twice in this case, the user won’t see the intermediate state. Use this pattern with caution because it often causes performance issues

127
Q

When will componentDidUpdate() not be invoked?

A

componentDidUpdate() will not be invoked if shouldComponentUpdate() returns false.

128
Q

What happens when setState() is called within componentDidUpdate(), without encapsulating it in a conditional statement?

A

Performance Issues: Causes an infinite loop and triggers additional render().

129
Q

When is getDerivedStateFromProps called?

A

getDerivedStateFromProps is invoked right before calling the render method, both on the initial mount and on subsequent updates. It should return an object to update the state, or null to update nothing.

130
Q

When is getSnapshotBeforeUpdate() called?

A

getSnapshotBeforeUpdate() is invoked right before the most recently rendered output is committed to e.g. the DOM. It enables your component to capture some information from the DOM (e.g. scroll position) before it is potentially changed. Any value returned by this lifecycle will be passed as a parameter to componentDidUpdate().

131
Q

Which lifecycle method replaces componentWillReceiveProps?

A

componentWillReceiveProps was the only way to update state in response to a change in props without an additional render. In version 16.3, we introduced a replacement lifecycle, getDerivedStateFromProps to solve the same use cases in a safer way.

132
Q

What is the purpose of getDerivedStateFromProps()

A

getDerivedStateFromProps exists for only one purpose. It enables a component to update its internal state as the result of changes in props.

133
Q

What is meant by “Single Source of Truth”

A

It means that state should be elevated or lifted up to the “lowest common ancestor” of the components that need or uses that state.

Using this technique, when any part of that ancestor state changes it will automatically update the props of it’s child components, and the changes will flow down in one direction from top to bottom – always synchronized, never duplicated.

134
Q

Why should you avoid adding side-effects in getDerivedStateFromProps()

A

getDerivedStateFromProps may be called multiple times for a single update, so it’s important to avoid any side-effects. Instead, you should use componentDidUpdate, which executes only once after the component updates.

135
Q

What is the difference between getDerivedStateFromProps() and componentWillRecieveProps()?

A

Instead of calling setState, getDerivedStateFromProps simply returns an object containing the updated state. Also getDerivedStateFromProps() contains no side-effects.

136
Q

What is the purpose of the constructor function in a component?

A

To initialize state and to bind functions

137
Q

What arguments are passed into getDerivedStateFromProps()?

A

props and state

getDerivedStateFromProps(props,state)

138
Q

What does getDerivedStateFromProps() return?

A

an object to update the state of the component or null

139
Q

What is the function of the getDerivedStateFromProps() lifecycle method?

A

Essentially, this method allows a component to update its internal state in response to a change in props, before the component renders

140
Q

What can the render method return?

A

returns html to the dom

Can return:

  1. Strings
  2. Numbers
  3. Elements/Components
  4. Arrays/Fragments
  5. Null
  6. Portals
141
Q

What is the purpose of componentDidMount()?

A

The componentDidMount() method is called after the component is rendered.

This is where you run statements that requires that the component is already placed in the DOM.

142
Q

What is an alternative to shouldComponentUpdate() for preventing the re-render of a component?

A

pureComponent

143
Q

What is the purpose of getSnapshotBeforeUpdate()?

A

Used to grab information from the DOM just after the update is made, however, the value queried from the Dom will refer to the value just before the Dom is updated

so basically it takes a snapshot of the real DOM, after the virtual DOM has been updated and just before the Real DOM updates and you see the visual changes in the UI

144
Q

Which lifecycle method does getSnapshotBeforeUpdate work with?

A

in concjunciton with componentDidUpdate

getSnapshotBeforeUpdate returns either a value or null, which is passed into componentDidUpdate as a third argument

145
Q

What is the the signiture for componentDidUpdate?

A

componentDidUpdate(prevProps, prevState, snapshot) {

}

146
Q

What is the signiture for getSnapshotBeforeUpdate()?

A

getSnapshotBeforeUpdate(prevProps,prevState)

147
Q

What is a common usecase for getSnapshotBeforeUpdate()?

A

Autoscroll

148
Q

What are common usecases for componentWillUnmount?

A

removing:

  • event listeners
  • subscriptions
  • network requests
  • timers
149
Q

What is a single page app?

A

An app where the browser handles the transition between pages, instead of a server.

150
Q

Why is it important for an SPA ‘s content to be controlled by the URL?

A

So that it can be bookmarked. Bookmarks are only URLs and cannot record the state of a page.

When content is not controlled by the URL, then it cannot be bookmarked

151
Q

How to turn a REACT app into a SPA?

A

React Router

152
Q

What is REACT Router?

A

React Router is a collection of navigational components that compose declaratively with your application.

153
Q

Which library is used to install router for the dom

A

yarn add react-router-dom

154
Q

What is the function of ?

A

Listens for changes in the browser url and ensures that the right screen shows up.

returns a history object which will listen to changes in the URL

155
Q

Where (which file) should BrowserRouter be imported and setup?

A

index.js or in the file that calles ReactDOM.render()

Wrap the element in inside the ReactDOM.render() method

156
Q

What is the history api?

A

provides a minimal API that lets you manage the history stack, navigate, confirm navigation, and persist state between sessions.

157
Q

What is the purpose ot the component?

A

When the user clicks on the link, It talks to the BrowserRouter and tells it to update the URL

158
Q

What props needs to be passed to the link component?

A

the pathname

profile

or (if you need to pass more info)

Courses

159
Q

What is the puropose of ?

A

Route matches URL to compents, and will render components based on the URL.

160
Q

In regards to , when should we use render and when should we use component?

A

Use render when you want to pass props to the component.

Use component when no props are needed.

161
Q

Which properties should be passed to ?

A

Path and component (or render)

162
Q

Which keyword is used to ensure an exact match between the path and url?

A

exact

163
Q

What method could be use d to build a SPA instead of using the react-router-dom library?

A

use short-circuit logic and gaurds to conditionally render components, however this will not update or track the browser stack, which could make navigation and bookmarking a challenge

164
Q

What is serialization?

A

In computing, serialization (US spelling) or serialisation (UK spelling) is the process of translating a data structure or object state into a format that can be stored (for example, in a file or memory data buffer) or transmitted (for example, across a computer network) and reconstructed later (possibly in a different computer environment).[1] When the resulting series of bits is reread according to the serialization format, it can be used to create a semantically identical clone of the original object.

This process of serializing an object is also called marshalling an object in some situations.[1][2] The opposite operation, extracting a data structure from a series of bytes, is deserialization, (also called unserialization or unmarshalling).

165
Q

How to serialize form data with vanilla js?

A
var form = document.querySelector('form');
var data = new FormData(form);

That’s it! The FormData() constructor returns a FormData object of key/value pairs from your form fields.

Form fields must have a name property, or they’ll be skipped. Just an id won’t work.

166
Q

What happens natively in forms when you click submit?

A

Forms serialize the values into the url

167
Q

How to get setState() to behave sync, instead of async?

A

//Wrap it in a function that returns a promise

function setStateSynchronous(stateUpdate) {
        return new Promise(resolve => {
            this.setState(stateUpdate, () => resolve());
        });
    }
    async function foo() {
        // state.count has value of 0
        await setStateSynchronous(state => ({count: state.count+1}));
        // execution will only resume here once state has been applied
        console.log(this.state.count);  // output will be 1
    }
168
Q

Can we use await on setState()?

A

setState() does not return a “promise”. It seems setState() could return a promise since setState() acts as asynchronous. However, it does not. React setState() is a function that mutates the component state. This component state is a variable that stores a certain value or function of a given component. And setState() is used to update this component state.

169
Q

Does setState() update state immediatly?

A

Fact: setState() actions are asynchronous. According to the documentation of setState()

setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value. There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains.

setState() updates the state and will lead to re-rendering unless there are no differs from the previous state.

WhatsetState() does is reconciliation, the process of re-rendering the components tree. This allows us to have multiple calls to setState in a single scope and preventing unnecessary re-renders of the whole tree.

170
Q

How can we ensure that something is done only aftery after state has been updated.

A

uset the callback function on setState()

this.setState({state:updated},()=>{//do something})