useState

Using a state

const[n, setN] = React.useState(0)
const[user, setUser] = React.useState({name:'F'})
Copy the code

Note 1 — Cannot be locally updated

If state is an object, can I partially setState?

No, sample code

add. user, copy the previous properties

Because setState won’t help us merge properties, and useReducer won’t merge properties

Note 2 — The address remains the same

SetState (obj) If the obj address does not change, React assumes that the data has not changed

Address invariant example, name does not change

UseState receiver function

Const [state, setState] = useState(() => ({return initialState})) // This function returns the initial value of state and is executed only onceCopy the code

The advantage of writing the initial values as functions in useState is to reduce unnecessary computation (functions are executed only when needed).

SetState accepts the function

setN(i => i + 1)
Copy the code

Code sample

useReducer

useReducer

To practice the ideas of Flux/Redux

The sample code

In four steps —

  1. Create an initial valueinitialState
  2. Create all operationsreducer(state, action)
  3. To pass touseReducerGet read and write apis
  4. Call write ({type:’ operation type})

In summary, useReducer is a sophisticated version of useState

An example form with useReducer

The sample code

Instead of a story

steps
  1. Put the data together in onestoreobject
  2. Focus all operations onreducer
  3. To create aContext
  4. Create reads and writes to dataAPI
  5. Put the content of step 4 into step 3Context
  6. withcontext.ProbiderwillContextProvided to all components
  7. For each componentuseContextRead and write access toAPI
example

The sample code

Modularize

useContext

context

A global variable is a global context

Context is a local global variable

Method of use

We’ve seen examples before

  1. useC=createContext(initial)Create context
  2. use<C.provider>Define the scope
  3. Used within scopeuseContext(C)To use context

Code sample

UseContext Precautions

It’s not reactive

If one module changes the value of C, the other module does not perceive the change

useEffect & useLayoutEffect

useEffect

Side effects

Changes to the environment are side effects, such as modifying document.title

However, it is not necessary to include side effects in useEffect

UseEffect runs after each render

use

Used as componentDidMount, [] as the second argument

Used as componentDidUpdate to specify dependencies

Code sample

Used as componentWillUnmount, via return

Code sample

The above three uses can exist simultaneously

The characteristics of

If multiple USEeffects exist at the same time, they are executed in the order in which they occur

useLayoutEffect

Layout side effect

UseEffect is executed after the browser rendering is complete

example

UseLayoutEffect is executed before the browser renders

Prove it laterally through time points

The characteristics of

UseLayoutEffect is always executed before useEffect

Tasks in useLayoutEffect best affect Layout

experience

UseEffect is preferred for user experience

useMemo

React.memo

React defaults to redundant render

Replace the Child in the code with react.Memo (Child)

If the props are unchanged, there is no need to execute a function component again

The final result

The React. Memo bug

Have a bug

In the example above, because of the listener added to Child, the App will execute line 12 again to generate the new function

That is, although the old and new functions have the same function, the address is different

Solution: Use useMemo

useMemo

The characteristics of

The first argument is ()=>value, as defined

The second argument is dependent on [m,n]

A new value is computed only when the dependency changes

If the dependency does not change, reuse the previous value

This function is equivalent to computed for Vue2

Pay attention to

If value is a function, useMemo(()=>(x)=>console.log(x))

This is a function that returns a function

Syntax sugar useCallback can be simplified

useCallback

UseCallback (x = > log (x), [m]) / / equivalent to the useMemo (() = = > > x log (x), [m])Copy the code

useRef

purpose

If a value is required, it remains the same as the component is rendered

Code sample

Const count = useRef(0) // read count.currentCopy the code

Why current?

To ensure that useRef is the same value both times (only for references)

extension

The ref Vue3

// initialize const count = ref(0) // read countCopy the code

Difference: Vue3 automatically render when count.value changes

Can useRef automatically render on changes?

The sample code

Log (count.current), but button ‘ ‘update count: 0’ does not change. UseRef cannot automatically render

No, it doesn’t fit the React philosophy, which is UI equals f of data.

If you want this function, you can add — yourself

Rewrite the code

Listen for ref and call setX when ref. Current changes

forwardRef

Code sample

Code 1: Props cannot pass the ref attribute

Code 2: Implement the ref pass

Code 3: The ref is passed twice to get a reference to button

useRef

Can be used to reference DOM objects

It can also be used to refer to ordinary objects

forwardRef

Because the PROPS does not contain ref, the forwardRef is required

Why doesn’t props include ref?

Because most of the time you don’t

useImperativeHandle

Code sample

Do not use the code used imperativeHandle

The useImperativeHandle code is used

Analysis of the

Attributes used to customize ref

Customize the Hook

Encapsulating data operation

A simple example

Close case

Analysis of the

You can also use Context in custom hooks

UseState only says it can’t run inside an if, not a function, as long as the function is run inside a function component

Stale Closure

Outdated closure

Reference article links