React Flashcards
Why React?
Fast
Extensive library
Active community
Compositional/Modular
Declarative
Unidirectional Dataflow
just javascript
What is a simple server we can setup for development
npm i -g live-server
live-server public
What is Babel?
Javascript compiler
Compiles jsx into es5
Why can if statements not be used in templates but a ternary can?
Because a ternary is an expression while if statements is a statement or controll structure. ONLY expressions can be used in jsx.
What are 3 things that are ignored by jsx?
undefined, null and booleans
How to add conditional logic to jsx?
- Ternary expressions
- Logical && operator
- Logical || operator
- Define a function outside of the template that handles conditional logic and then call the funciton in jsx
Difference between var, let, const.
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.
What needs to happen before the browser can read jsx?
The jsx code or file needs to be transpiled in javascript. This is done through babel.
difference between arrow functions and function declarations and expressions
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
What needs to be done for a es5 function to use it’s parent’s this value
const that = this
function(){ that.value }
How are the attributes in jsx different from html attributes
class = className
use camelCase instead of hyphens
form-target = formTarget
JSX does not have built in data binding, what does this mean?
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.
What is data-binding?
Keeping state in sync with views
How to turn a value into a boolean
!!value
How to turn a value into a boolean
return !!value
In order to create a component what must an es6 class extend?
React.component
What is the one method tha t must be defined in a React componenent class?
render(){
return (
)
}
How to get a value from the input field
add name=”someName” attribute to the input field
in the event handler get the value with:
e.target.elements.someName.value
how to bind a method in a class component
//in constructor this.methodName = this.methodName.bind(this)
How to set default state in a component
//in constructor this.state = { key:value }
How to change or update state?
this.setState((prevState)=>{ return { key: prevState.value + 1 } })
What is the difference between a class based component and a stateless functional component?
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 to add default props to a component?
Header.defaultProps = {
key:’some value’
}
LIfecycle of a component
- coponentWillMount -executes before initial rendering
- componentDidMount - imediately after the initial rendering
- componentWillRecieveProps - When component recieves new props
- shouldComponentUpdate -before rendering, after receiving new props or state
- componentWillUpdate -after shouldComponentUpdate returns true
- componentDidUpdate - after rerender
- .componentWillUnmount -just before removing component from Dom
Which babel dependencies needs to be installed?
@babel/cli @babel/core @babel/preset-env @babel/preset-react babel-loader
What is webpack
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.
Webpack setup
install webpack and webpack cli
create a webpack.config.js file
webpack configuration
//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 to configure webpack to work with babel?
- install babel dependencies
- @babel\cli
- @babel\core
- @babel\preset-env
- @babel\preset-react
- babel-loader - Add module to weppack.config.js file
module:{
rules:[{
loader:’babel-loader’,
test:/.js$/,
exclude:/node_modules/
}]
},
- Setup .babelrc file and configure presets
{ "presets":[ "@babel/env", "@babel/react" ] }
- update scripts in package.json
“build”:”webpack”
How to setup dev server with webpack
- install webpack-dev-server
- add devServer to wepack.config.js file
devServer:{
contentBase: path.join(__dirname,’public’)
}
- create Script in package.json
“dev-server”:”webpack-dev-server”
How to access children of a component
props.children
Difference between server-side routing and client-side routing?
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 to setup webpack to process scss and css files?
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 to add a favicon to html page?
When using webpack, what needs to be added to the html file?
What is React Fiber ?
Fiber is the new reconciliation engine in React 16. Its main goal is to enable incremental rendering of the virtual DOM.
What is the ‘virtual Dom”?
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
Explain reconciliation
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
What is the architecture of the React library?
MVC
model -components
View - the ui
controller - user input
What data structure does the REACT virtual DOM use?
Tree structure
Explain the diffing algorithim?
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
Why use Redux?
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
What is Redux?
A Global State Container
Which redux method runs everytime a change is made to the store and can be used to track changes?
const unsubscribe = store.subscribe(()=>{ console.log(store.getState().count) })
store.dispatch({
type:’INCREMENT’
})
unsubscribe();
When destructuring an object, how can one set defualts in the event that the property does not exist within the object?
const person = { name: "david", age: 21 }
const {name, age = ‘unknown’} = person
When destructuring an object, how can one change the property name?
const person = { name: "david", age: 21 }
const {name: firstName, age: biologicalAge} = person
How to destructure an array?
const address = [‘102 Palian Street’, ‘Oanang’,’Krabi’,’95000’]
const [street,city,state,zip] = address
2 attributes of reducers
- reducers are pure functions
2. Never change state or actions
When updating state arrays in react or redux, why should we use .concat or the spread opperator instead of .push?
Because push will modify the original array, whereas .concat returns a new one
which babel plugin enables the use of object spread opperators?
babel-transform-object-rest-spread
What are higher order components?
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.
What are the main components of Redux?
Store
Reducers
Action Generators
Selectors
How to create a Redux store?
import {createStore} from ‘redux’
const store = createStore(countReducer)
How to create a redux reducer?
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 to create a redux action generator?
const incrementCount = (value=1) => { return { type: 'INCREMENT', incrementBy: typeof value === 'number' ? value : 1 } }
How to perform an action on a redux store?
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 to create a selector that filters the data in a redux store?
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 && endDateMatch && textMatch; }).sort((a,b)=>{ if(sortBy === 'date') { return a.createdAt < b.createdAt ? 1:-1; }else{ return a.amount < b.amount ? 1:-1; } }); }
How to combine redux reducers into one store?
import {createStore, combineReducers} from ‘redux’
const store = createStore( combineReducers({ expenses: expensesReducer, filters:filtersReducer, }) );
How to create a higher order component?
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’))
What library can be used instead of working with the Date() api?
yarn add moment
How to get a timestamp from the moment library?
const now = moment() now.format()
steps to creating a production build
- Update webpack.config.js file
- set mode to production
- set devtools to ‘source-map’ if in production otherwise set it to ‘inline-source-map’ - set build script
- “webpack -p –env production”
3 minify css
- yarn add mini-css-extract-plugin
4.Setup Express server
setup redux to work with react
- 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);
- update state from componenents by accessing props.dispatch and dispatching the relevant action generators
What are webHooks?
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.
What does calling useState do?
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.
What do we pass to useState as an argument?
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.)
What does useState return?
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.
Different Webhooks
useState() useReducer() useEffect() useLayoutEffect() useReg() useCallback() useContext()
What does Effect Hooks do?
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.
When does the useState hook bail out of rerendering?
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.)
When do effect hooks run?
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.
How to run useEffect conditionally?
By adding an array of dependencies as a second argument.
useEffect( () => { const subscription = props.source.subscribe(); return () => { subscription.unsubscribe(); }; }, [props.source], );
How is useState() different from setState?
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.
What are some uses for useEffect()
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
Difference between useEffect() and lifecycle methods like componentDidMount()?
unlike lifecycle methods which can only defined once, multiple useEffect statements can be defined in a functional component
How to get useEffect() to run only once?
pass in an empty array as the second argument
how to get useEffect() to run conditionally?
pass in an array of conditions as the second argument
How to run useEffect() just before a component is removed to cleanup code?
inside the callback function return another function which runs the cleanup code
Difference between redux and useReducer()
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
How to create a context hook?
//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)
}
What are fragments?
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.
When using useState it is usually better to use separate statements for each item being managed, except when…
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.
What does React.memo() do?
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
What does useCallback do?
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).
What is the most common use of the useCallback hook?
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.
What is the class based equivalent to React.memo()?
Extend PureComponent class or define a custom implementation of shouldComponentUpdate() method if you need memoization for class-based components.
What is the useRef() hook used for?
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.
What is the difference between useRef and createRef
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
How to access a dom element by using createRef
const x = React.createRef()
function focusInput(){
x.current.focus() //accesses the dom element.
}
Difference between imperitive and declarative programming
“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
Two-way data-binding and it’s problems
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.
Uni-directional data flow within React
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!).
What is the difference between REACT and other frameworks, when it comes to building the user interface?
REACT doesn’t use strings, but rather builds the UI out of simple javascript objects.
React.createElement( /* type /, / props /, / content */ );
What is the relationship between React.createElement and the dom?
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.
How does the Single Responsibillity principle apply to components?
a component should ideally only do one thing. If it ends up growing, it should be decomposed into smaller subcomponents.
Three questions for distinguishing between State and props
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.
Which component should own the state?
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.
Describe the process of component thinking
- Break the UI into a component hierarchy (atomic design)
- Build a static version in REACT
- Identify The Minimal (but complete) Representation Of UI State
- Identify where the state should live
- Add inverse data flow
What is the “Single Responsibility Principle” and how does it apply to REACT components?
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.
Why is the process of rendering decoupled from the content being rendered?
Decoupling makes it possible to render on different devices: Servers, Dom, VR environments
What are components
Conceptually, components are like JavaScript functions. They accept arbitrary inputs (called “props”) and return React elements describing what should appear on the screen.
How to see the props being passed into a component?
console.log(“Props”, this.props);
Biggest difference between state and props?
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).
Why should we not use props to defining intial state?
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.”
What is reconcilliation?
process of determining what has changed in the previous and new outputs
What arguments can be passed into setState()?
- A function that takes prevState as an argument (used when updating a state)
- An object (used when replacing a state)
What is propTypes?
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
}
Difference between controlled and uncontrolled components?
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.
How should forms be handled in REACT?
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.
What is the setState signiture?
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.
should state be modified directly, using this.state = newState?
No, modifying state directly will not trigger a re-render of the components
Use setState() instead
is setState synchronous or Asynchronous?
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.
setState() doesn’t change or update state immediately. How can we ensure that code runs only after the state has been updated?
- Using componentDidUpdate
componentDidUpdate(prevProps, prevState) {
console.log(this.state.orders); // Prints out: 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 } );
Why should this.state not be used to update or increment existing state?
because setState is Async. and state is not changed immediately. instead, use prevState
this.setState((prevState, props) => ({
orders: prevState.orders + props.increment
}));
Why should we not perform mulitple setState() calls in the same render cycle?
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 }));
What are anti-patterns
Anti-patterns are certain patterns in software development that are considered bad programming practices.
Why should we bind custom functions in the constructor instead of when we pass it as a prop to another component?
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.
What is meant by side-effects in React, and which method should be free of side-effects?
“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
In what order are lifecycle methods called when a component mounts?
constructor()
static getDerivedStateFromProps()
render()
componentDidMount()
Which three lifecycle methods are now considered legacy code and unsafe?
componentWillMount()
componentWillUpdate()
componentWillReceiveProps()
In what order are lifecycle methods called when a components updates?
static getDerivedStateFromProps() shouldComponentUpdate() render() getSnapshotBeforeUpdate() componentDidUpdate()
In what order are lifecycle methods called when a components are removed?
componentWillUnmount()
Which lifecycle method removes a component from the DOM?
componentWillUnmount()
Which lifecycle method prevents a component from re-rendering?
render() will not be invoked if shouldComponentUpdate() returns false.
Which lifecycle methods are best for handling subscriptions?
componentDidMount() for creating subscriptions
componentWillUnmount() for removing or closing subscriptions
What happens when setState() is called within the componentDidMount() method.
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
When will componentDidUpdate() not be invoked?
componentDidUpdate() will not be invoked if shouldComponentUpdate() returns false.
What happens when setState() is called within componentDidUpdate(), without encapsulating it in a conditional statement?
Performance Issues: Causes an infinite loop and triggers additional render().
When is getDerivedStateFromProps called?
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.
When is getSnapshotBeforeUpdate() called?
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().
Which lifecycle method replaces componentWillReceiveProps?
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.
What is the purpose of getDerivedStateFromProps()
getDerivedStateFromProps exists for only one purpose. It enables a component to update its internal state as the result of changes in props.
What is meant by “Single Source of Truth”
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.
Why should you avoid adding side-effects in getDerivedStateFromProps()
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.
What is the difference between getDerivedStateFromProps() and componentWillRecieveProps()?
Instead of calling setState, getDerivedStateFromProps simply returns an object containing the updated state. Also getDerivedStateFromProps() contains no side-effects.
What is the purpose of the constructor function in a component?
To initialize state and to bind functions
What arguments are passed into getDerivedStateFromProps()?
props and state
getDerivedStateFromProps(props,state)
What does getDerivedStateFromProps() return?
an object to update the state of the component or null
What is the function of the getDerivedStateFromProps() lifecycle method?
Essentially, this method allows a component to update its internal state in response to a change in props, before the component renders
What can the render method return?
returns html to the dom
Can return:
- Strings
- Numbers
- Elements/Components
- Arrays/Fragments
- Null
- Portals
What is the purpose of componentDidMount()?
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.
What is an alternative to shouldComponentUpdate() for preventing the re-render of a component?
pureComponent
What is the purpose of getSnapshotBeforeUpdate()?
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
Which lifecycle method does getSnapshotBeforeUpdate work with?
in concjunciton with componentDidUpdate
getSnapshotBeforeUpdate returns either a value or null, which is passed into componentDidUpdate as a third argument
What is the the signiture for componentDidUpdate?
componentDidUpdate(prevProps, prevState, snapshot) {
}
What is the signiture for getSnapshotBeforeUpdate()?
getSnapshotBeforeUpdate(prevProps,prevState)
What is a common usecase for getSnapshotBeforeUpdate()?
Autoscroll
What are common usecases for componentWillUnmount?
removing:
- event listeners
- subscriptions
- network requests
- timers
What is a single page app?
An app where the browser handles the transition between pages, instead of a server.
Why is it important for an SPA ‘s content to be controlled by the URL?
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
How to turn a REACT app into a SPA?
React Router
What is REACT Router?
React Router is a collection of navigational components that compose declaratively with your application.
Which library is used to install router for the dom
yarn add react-router-dom
What is the function of ?
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
Where (which file) should BrowserRouter be imported and setup?
index.js or in the file that calles ReactDOM.render()
Wrap the element in inside the ReactDOM.render() method
What is the history api?
provides a minimal API that lets you manage the history stack, navigate, confirm navigation, and persist state between sessions.
What is the purpose ot the component?
When the user clicks on the link, It talks to the BrowserRouter and tells it to update the URL
What props needs to be passed to the link component?
the pathname
profile
or (if you need to pass more info)
Courses
What is the puropose of ?
Route matches URL to compents, and will render components based on the URL.
In regards to , when should we use render and when should we use component?
Use render when you want to pass props to the component.
Use component when no props are needed.
Which properties should be passed to ?
Path and component (or render)
Which keyword is used to ensure an exact match between the path and url?
exact
What method could be use d to build a SPA instead of using the react-router-dom library?
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
What is serialization?
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).
How to serialize form data with vanilla js?
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.
What happens natively in forms when you click submit?
Forms serialize the values into the url
How to get setState() to behave sync, instead of async?
//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 }
Can we use await on setState()?
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.
Does setState() update state immediatly?
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.
How can we ensure that something is done only aftery after state has been updated.
uset the callback function on setState()
this.setState({state:updated},()=>{//do something})