A preface
Hello, everyone, I’m an alien 👽. On August 24th, I participated in an online technical sharing of the React System Review how to be the Most Efficient as a sharing guest. Next, I will share the contents of the live broadcast with you. In the process of sharing, also enumerated some thinking questions and some popular interview questions, together with the post.
Here I am very grateful to the Nuggets platform for providing an opportunity to share technology, and also for the enthusiastic support of digging friends. Overall, it was a success. Maybe I was nervous at the beginning, because it was the first live broadcast after all, and the first live broadcast of my life was dedicated to the Nuggets 😂. Here are some screenshots saved during the live broadcast. As a whole, digger was very helpful and also participated in the interaction and asked a lot of questions.
Live scene:
Interactive scene of digging friends
If you want to see a live replay of the children’s shoes, please click here: live replay
Ok, without further ado, let’s get to the point. This live broadcast is mainly based on the following modules. These modules are my experience summarized in the past few years.
- React base module.
- React optimizes the method.
- React Ecological Mastery.
- React Design mode.
- React core principles.
- React project practice.
Two Knowledge point combing
The above modules are refined and summarized as follows:
React Base module:
- operation
jsx
。 - Master classes and function Components.
- State update mechanism,
setState
å’ŒuseState
The usage and difference between. - understand
props
What can be props in React? - Class component lifecycle, function component lifecycle alternatives,
useEffect
å’ŒuseLayoutEffect
. Ref
What is it? What can be done?css in React
.
React optimization method
- Render control.
- Render tuning.
- Processing massive amounts of data.
- Details.
The React of ecological
- The React to the Router.
- The React – story.
- The React – Mobx.
- Project engineering umi | dva and so on.
React Design Mode
- Combination mode.
- Render props mode.
- HOC | decorator pattern.
- Provider pattern.
- Custom hooks schema.
React Core Principles
- Principle of events.
- Harmonic principle.
- Scheduling principles.
- Principle of hooks.
- Diff process and so on.
The React of actual combat
- Implement the form system.
- Implement status management tools.
- Implement the routing function.
- Custom hooks practice.
These are the things you should learn about React. Let me summarize it with a picture.
The next step is to disassemble each function.
Three function disassembly
The content of the share is refined into each function point we need to master, in the form of questions, we can try?
1 React Base module
Base module JSX
JSX summary of knowledge points:
- What happened to the JSX syntax we wrote? React JSX -> React Element -> React Fiber process.
- React element?
- React () React ()
import React from 'react'
function Index(){
return <div>let us learn React!</div>
}
Copy the code
-
4. How to operate React Element to make it controllable? React createElement and React cloneElement.
-
⑤ The difference between createElement and cloneElement.
-
React Children React Children Map, forEach, count, toArray, only.
-
⑦ JSX development sample:
function Test(num){
console.log(num)
useEffect(() = >{
console.log('1111')
},[])
return <div>React Advanced Practice Guide</div>
}
export default function Index(){
const [ isShow , setIsShow ]= useState(false)
return <div>
<button onClick={()= >setIsShow(! > click isShow)}</button>
{isShow ? <Test num={1} /> : <Test num={2} />}
</div>
}
Copy the code
UseEffect console.log(‘1111’) is printed by clicking button.
Error analysis: Click the button, toggle isShow, control mount | unmount of two Test components, because components are mounted repeatedly, then useEffect executes, prints console.log(‘1111’), but is this the actual result?
Effect:
Flow analysis: Why is console.log not printed in useEffect?
- The two Test components are essentially processed by Babel as two Element objects.
element
The type attribute in the object refers to the Test component function. The only difference between the two Element objects is that the props are different.
- In the React phase, if the type refers to the same object as React, it can be judged that they are components. Therefore, the update logic of React is only the change of the judged props.
- Then in the Test function, updating the component does not make the dependency
[]
çš„useEffect
Execute again, soconsole.log('1111')
It will not be printed.
Solve a problem:
If you want the component to mount | unmount effect, you can simply add a key to Test. The key can be used as component identification. In the next update, the reusable fiber node will be found based on the key. The normal component mount | unmount process is then followed.
{isShow ? <Test num={1} key={1} /> : <Test num={2} />}
Copy the code
Basic module State
Knowledge points summarized in state:
- â‘ State update mechanism? State changes to the view update process.
- â‘¡ Why is the state batch update rule broken?
- â‘¢ Is setState synchronous or asynchronous?
- Class 4 components
setState
And function componentsuseState
What are the similarities and differences? - ⑤ State management method of function components useState + useRef? UseState is responsible for updating and useRef is responsible for saving the state.
- â‘¥ State print problem:
handleClick=() = >{
setTimeout(() = >{
this.setState({ number: 1})})this.setState({ number: 2 })
ReactDOM.flushSync(() = >{
this.setState({ number: 3})})this.setState({ number: 4})}render(){
console.log(this.state.number)
return <button onClick={ this.handleClick } >Click on the</button>
}
Copy the code
Click the button to print the order?
Print 3, 4, 1. I think it’s easy to see why.
First flushSync enclosing setState ({3} number:) has a high-priority updates, so 2 and 3 be batch update to 3, so 3 to be printed. Update to 4. Finally update setTimeout with number = 1.
Base module Component
The Component module contains knowledge:
- Class component characteristics, function component characteristics, what is the difference between the two?
- (2) How does the component communicate?
- How to strengthen the components?
- Do you React to components and when do you process them?
- ⑤ Design specifications for common components?
Base module life cycle
Life cycle
- â‘ Introduction to life cycle, and usage?
- (2) The execution time of the life cycle? What is the execution order of the parent and child life cycles?
- â‘¢ What are the alternatives to the life cycle of function components?
- â‘£ What is the difference between useEffect and useLayoutEffect?
- ⑤ Why scrap the life cycle?
One diagram shows the execution timing of all life cycles of function components and class components (including obsolete life cycles) :
Base module Ref
Ref Knowledge summary:
- (1) Ref object, and two ways to create Ref object. UseRef and createRef
- â‘¡ What is the role of Ref? 1. Get component instance, DOM element; 2 component communication; 3 Save state;
- â‘¢ Ref principle?
commitAttachRef
å’ŒcommitDetachRef
. - â‘£ Three ways to obtain Ref? The function; Ref object; The String;
- ⑤ How to pass ref across levels?
- â‘¥ How does the parent obtain the internal state of the function’s child components?
Basic module Css in React
Summary of CSS modules:
- 1 React CSS modular solution.
- â‘¡ CSS Module mastery.
- â‘¢ Master CSS in JS.
2 React Optimization method
React optimization method summary:
- React render control method? . React Element, pureComponent, Memo, shouldComponentUpdate
- â‘¡ shallowEqual shallow comparison principle.
- â‘¢ Application of throttling and anti-shaking in React.
- (4) Rational use of state management.
- ⑤ Introduce as needed. Reduce project volume.
- Code segmentation lazy, asynchronous component Suspense and its principle.
- Diff algorithm, reasonable application of key.
- ⑧ Render error boundary,
componentDidCatch
. - ⑨ Use the status management tool and immutable. Js.
- â‘© useMemo cache logic.
- ⑪ Memo’s cache strategy.
3 the React of ecological
React router, React -redux, React – Mobx umi DVA, etc.
- â‘ Two routing modes | SPA Single page routing principle.
- React Router Implements dynamic routing and custom routing.
- â‘¢ Route. Router Switch.
- 4 permission route encapsulation.
- ⑤ Use mox-react.
- â‘¥ Mobx vs. React Redux?
- ⑦ Mobx principle, collecting dependencies, triggering updates.
- 8 React Redux and Redux.
- ⑨ Redux design Pattern | Middleware Principles.
- â‘© React Redux principle?
- Derivative: DVA React-Saga, etc
- Hence the connect principle in the following Redux.
4 React Design mode
React Design Patterns
- React Design Patterns Composite mode, Render props mode, Provider mode, Hoc mode, custom hooks mode.
- â‘¡ New and old version context usage features.
- React Context features. Layer by layer, publish and subscribe.
- â‘£ The new version of context consumers in several ways. ContextType, useContext, consumer
- ⑤ Are the advantages and disadvantages of the two ways of hoc? Property proxy, reverse inheritance.
- â‘¥ How hoc solves the problem of static attribute inheritance.
- ⑦ How hoc to solve the problem of ref acquisition.
- ⑧ hoc Notes.
- ⑨ Custom hooks design.
- â‘© Custom hooks practices.
Here are some code snippets of classic design patterns for your reference:
Portfolio model
<Form ref={ form } >
<FormItem name="name" label="I am" >
<Input />
</FormItem>
<FormItem name="mes" label="I want to say to all of you." >
<Input />
</FormItem>
<input placeholder="Unwanted input" />
<Input/>
</Form>
Copy the code
Provider pattern
function ConsumerDemo(){
const { color,background } = React.useContext(ThemeContext)
return <div style={{ color.background}} >consumers</div>
}
const Son = React.memo(() = > <ConsumerDemo />) / / child component
const ThemeProvider = ThemeContext.Provider / / provider
export default function ProviderDemo(){
const [ contextValue , setContextValue ] = React.useState({ color:'#ccc'.background:'pink' })
return <div>
<ThemeProvider value={ contextValue } >
<Son />
</ThemeProvider>
<button onClick={() = >SetContextValue ({color:'# FFF ', background:'blue'})} > Toggle the theme</button>
</div>
}
Copy the code
Render props model
const Index = () = >{
return <Container>
<Children />
{ (ContainerProps)=> <Children {. ContainerProps} name={'haha'} / > }
</Container>
}
Copy the code
Hoc mode
@HOC1(styles)
@HOC2
@HOC3
class Index extends React.Componen{
/ *... * /
}
Copy the code
Custom hooks schema
function useXXX(){
const value = React.useContext(defaultContext)
/ *... Initialize logic */ with value in the context
const newValue = initValueFunction(value) /* initialize value to get newValue */
/ *... * /
return newValue
}
Copy the code
5 React Core principles
React Core Principles:
Principle of fiber
- â‘ What is Fiber? What problems does the Fiber architecture solve?
- â‘¡ What is the difference between root and root Fiber?
- â‘¢ How is the connection between different fibers established?
- React reconcile flow?
- ⑤ What did commit and Render do in the two stages?
- â‘¥ What is a double buffer tree? What does it do?
- ⑦ Fiber depth traversal process?
- Can the harmonic of Fiber be interrupted? How to interrupt?
Scheduling principle
- â‘ Principle of asynchronous scheduling?
- React why not use setTimeout?
- React time sharding
- React How to simulate requestIdleCallback?
- ⑤ Briefly describe the scheduling process?
Principle of hooks
- Why do React Hooks have to be implemented inside function components? React can listen for React Hooks to execute externally and throw exceptions.
- How do React Hooks save state? Where is the saved information stored?
- React Hooks cannot be written in conditional statements.
- â‘£ Why does useMemo internal reference useRef not need to add dependencies while useState does?
- The useEffect callback function create is executed again.
- UseEffect and useEffect are different in React.
Principle of events
- Why does React have its own event system?
- â‘¡ What is event composition?
- â‘¢ How to achieve batch update?
- How does the event system simulate the bubbling and capturing phases?
- ⑤ How to find the matching fiber from dom elements?
- â‘¥ Why can’t return false be used to prevent the default behavior of events?
- Are events bound to the real DOM? How is not binding where?
- ⑧ What changes does V17 have to the event system
6 the React practice
Practice is the only criterion to test truth. If you want to advance React, you also need to try to code based on theoretical knowledge.
- If you haven’t done React projects before, try writing a demo.
- Try writing a common component.
- Try writing a higher-order component.
- Try writing a custom hooks.
- Try to use multiple design patterns in your projects.
7 React Learning stages
React Can be advanced in the following stages.
-
Stage 1: Understand the basic API, try to write projects, try some complex logical scenarios. Will use some React ecology.
-
Phase two: Try to encapsulate some basic components, Hoc, try to use some design patterns.
-
Stage 3: Learn some principles, you can try to look at the core source code.
-
Stage 4: You can write some libraries according to your business needs and consider open source.
Four summarizes
Learn how to learn React. Learn how to learn React. Learn how to learn React.
React Advanced Practice Guide
The knowledge points shared this time can find the answer in this small volume. The React Context will be updated in chapter 8 as the React version continues to be updated and maintained. I’d like to offer you a 30% discount code F3Z1VXtv on a first come, first served basis
Interested students can pay attention to the author’s public account: front-end Sharing continue to share front-end hard text.