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()