Advanced React
Reconciliation, keys, React.Children
28 flashcards · Programming Languages · by lakesare
In what order does componentDidMount of parents and children execute?
First in the deepest child, then up.
What is meant by reconciliation in react?
Reconciliation is the process that compares two react trees, and tries to update DOM efficiently. This is what happens when setState() is called: 1. React creates a new tree 2. diffs the new tree against the old tree 3. tries to update the DOM efficiently. 'Reconciliation' word is chosen because we try to match components from the old tree to the new tree. Links: reconciliation react docs
What 2 rules does React use during reconciliation?
1. different node types (custom or DOM) renderA: <Header/> renderB: <Content/> => [removeNode <Header/>], [insertNode <Content/>] Unmounts previous, and mounts new node [we don’t need to spend precious time trying to match two components that are unlikely to have any resemblance]. 2. same node type (custom or DOM) Component stays the same, its state is kept. componentWillReceiveProps() and componentWillUpdate() are called.
What's the use of the key attribute?
React uses the key to match children in the original tree with children in the subsequent tree. MOST IMPORTANTLY KEYS KEEP STATE WHERE IT'S DUE. Otherwise it would just go one-by-one. renderA: <ul> <li>a</li> <li>b</li> </ul> renderB: <ul> <li>hi</li> <li>a</li> <li>b</li> </ul> => [replace inner text a=>hi], [replace inner text b=>a], [insertNode <li>b</li>] And it's inefficient. To help React perform DOM updated in the minimum amount of steps - use the key attribute.
What is meant by controlled components?
When we keep component's state in the parent component. This is usually done to form elements, with onChange and value props. If you were to use uncontrolled components, you'd instead use ref.
When does React do setState() batching?
In event handlers: onClick(), and lifecycle methods: componentDidMount() React won't batch setStates in eg ajax calls.
setState() is async. How do you battle it?
this.setState((prevState, props) => ({ count: prevState.count + 1 })); But remember that async setState() is only a problem when you set your new state based on the previous one.
static propTypes = { hi: PropTypes.string.isRequired } What happens if hi = null?
1. static defaultProps will not be used. 2. Warning: Required prop hi was not specified warning will be made.
Is it okay to initialize state from props? constructor(props) { super(props); this.state = { formState: props.passenger }; }
It’s fine to initialize formState this way if your component doesn’t need to stay aware of potential changes in the props.passenger value .
<input onChange={(event) => {}}/> What's event here?
It's an instance of SyntheticEvent. That's a wrapper around browser's native event, but works the same across all browsers.
At what phase do event handlers trigger?
Bubbling.
Give an example of Composition VS Inheritance in React.
Composition is the usual stuff we do. We create a component, then use it inside other components. Inheritance on the other hand is something no one uses: class Form { render = () => <input name="salary"/> } class UpdateForm extends Form { render = () => <div> {super.render()} <button>Update</button> <div> } Links: code examples
Why should AJAX requests go to componentDidMount()?
You can’t guarantee the AJAX request won’t resolve before the component mounts. If it did, that would mean that you’d be trying to setState on an unmounted component.
What's the signature of React.cloneElement()?
React.cloneElement( element, [props], // will be merged with element's props shallowly [...children] // will replace existing children )
What is React.Children used for?
React.Children provides utilities for dealing with the this.props.children opaque data structure.
What will <h1 className="sss"><h2/><h3/></h1> compile to?
React.createElement( "h1", { className: "sss" }, React.createElement("h2", null), React.createElement("h3", null) ); React.createElement(tagName, props, ...children)
What will class Hello extends React.Component{} <Hello s="sss"/> compile to?
class Hello extends React.Components {} React.createElement(Hello, { s: "sss" });
How to make onClick={} event handler trigger in the bubble VS capture phase?
bubble phase: will trigger by default. capture phase: use onClickCapture={} instead.
What's passed in ref: <input ref={(ref) => { this.hi = ref; }}/> <SomeClass ref={(ref) => { this.hello = ref; }}/>
ref on HTML element: ref == DOM element ref on custom react class: ref == mounted instance of this component React will call the ref callback with the DOM element when the component mounts, and call it with null when it unmounts. When the ref attribute is used on an HTML element, the ref callback receives the underlying DOM element as its argument. When the ref attribute is used on a custom component declared as a class, the ref callback receives the mounted instance of the component as its arg…
<input ref={(input) => { this.textInput = input; }}/> When is ref function called?
If written as ref={this.refFunction}: when mounts - with DOM element/mounted instance when unmounts - with null If written as inline function: it will get called twice every render, first with null, and then again then the SAME instance/ DOM element. This is because a new instance of the function is created with each render, so React needs to clear the old ref and set up the new one. You can avoid this by defining the `ref` callback as a bound method on the class, but note that it shouldn't mat…
Can you define refs on functional components? <FunctionalComponent ref={(ref) => { this.hi = ref; }} const FunctionalComponent = (props) => <div>Hi!</div>;
No! Because they don't have instances. You may not use the ref attribute on functional components because they don’t have instances.You should convert the component to a class if you need a ref to it, just like you do when you need lifecycle methods or state.
Can you define refs inside of functional components? const FunctionalComponent = (props) => <div ref={(ref) => { this.rrr = ref; }}>Hi!</div>;
Yes, as long as you refer either to: HTML elements class components function CustomTextInput(props) { let textInput = null; function handleClick() { textInput.focus(); } return ( <div> <input type="text" ref={(input) => { textInput = input; }} /> <input type="button" value="Focus the text input" onClick={handleClick} /> </div> ); }
componentDidUpdate() When is it called? With what arguments?
after every update, EXCEPT for the initial render componentDidUpdate(prevProps, prevState)
Write a simple counter component using react hooks.
import React, { useState } from 'react'; function Counter() { const [count, setCount] = useState(0); return ( <div> <p>You clicked {count} times</p> <button onClick={() => setCount(count + 1)}> Click me </button> </div> ); }
What would one use instead of componentDidMount using react hooks?
useEffect, it's componentDidMount, componentDidUpdate, and componentWillUnmount combined. Does useEffect run after every render? Yes! By default, it runs both after the first render and after every update. Instead of thinking in terms of “mounting” and “updating”, you might find it easier to think that effects happen “after render”. React guarantees the DOM has been updated by the time it runs the effects. Passing no 2nd argument causes the useEffect to run every render. Then, when it runs, it…
What does passing an empty array to useEffect(fn, []) achieve?
It will only execute on mount and unmount! useEffect(() => { console.log('mounted'); return () => console.log('unmounting...'); }, [])
What does the second array argument achieve? useEffect( () => { const subscription = props.source.subscribe(); return () => { subscription.unsubscribe(); }; }, [props.source], );
This effect is only called when props.source changes.
How to use instead of shouldComponentUpdate in functional components since React 16.6?
React.memo(MyComponent, areEqual) function MyComponent(props) { /* render using props */ } function areEqual(prevProps, nextProps) { /* return true if passing nextProps to render would return the same result as passing prevProps to render, otherwise return false */ } export default React.memo(MyComponent, areEqual);