##useState | Set and change state, replacing the original state and setState |
useEffect | Instead of the original life cycle, the merged version of componentDidMount, componentDidUpdate and componentWillUnmount |
##useLayoutEffect
has the same effect as useEffect , but it will call effect synchronously |
|
useMemo
Control component update conditions, control method execution and optimize value transfer based on state changes |
|
useCallback
useMemo optimizes the value transfer, usecallback optimizes the transfer method, whether to update |
|
useRef
Same as the previous ref, It’s just more concise |
|
useContext
Context and deeper components pass values |
|
useReducer
Instead of the reducer in the original redux, use |
|
useDebugValue
with useContext to display the custom hook label in the React developer tools for debugging. |
|
useImperativeHandle
allows you to customize the instance value exposed to the parent component when using ref. |
|
1.useState
import React from 'react';
import './App.css';
//通常的class写法,改变状态
class App extends React.Component {
constructor(props){
super(props)
this.state = {
hook:'react hook 是真的好用啊'
}
}
changehook = () => {
this.setState({
hook:'我改变了react hook 的值'
})
}
render () {
const { hook } = this.state
return(
<header className="App-header">
{hook}
<button onClick={this.changehook}>
改变hook
</button>
</header>
)
}
}
export {App}
//函数式写法,改变状态
function App() {
//创建了一个叫hook的变量,sethook方法可以改变这个变量,初始值为‘react hook 是真的好用啊’
const [hook, sethook] = useState("react hook 是真的好用啊");
return (
<header className="App-header">
{hook}{/**这里的变量和方法也是可以直接使用的 */}
<button onClick={() => sethook("我改变了react hook 的值")}>
改变hook
</button>
</header>
);
}
export {App}
//箭头函数的函数写法,改变状态
export const App = props => {
const [hook, sethook] = useState("react hook 是真的好用啊");
return (
<header className="App-header">
{hook}
<button onClick={() => sethook("我改变了react hook 的值")}>
改变hook
</button>
</header>
);
};
Copy after login
Usage notes are in the demo above
After reading the comparison and use of useState above, a small The demo structure is clearer and the code is more concise. It is more like writing js code and applying it to the project. Wouldn't it be wonderful?
2.useEffect & useLayoutEffect
useEffect replaces the original life cycle, the merged version of componentDidMount, componentDidUpdate and componentWillUnmount
useEffect( ()=> ;{ return ()=>{ } } , [ ])
- The first parameter is a function. By default, it will be triggered when rendering and updating for the first time. By default, it comes with a return, return A function indicates that it can handle some things before it is destroyed.
- The second parameter, array [], when empty, means it will only be executed once and will not be triggered when updating. What are the parameters inside? It will only be executed when the parameters change. UseEffect will be executed
useEffect can be used multiple times, executed in sequence
useLayoutEffect Forces the execution of useeffect to be synchronous, and executes the internal function of useLayoutEffect first
import React, { useState, useEffect, useLayoutEffect } from 'react';
//箭头函数的写法,改变状态
const UseEffect = (props) => {
//创建了一个叫hook的变量,sethook方法可以改变这个变量,初始值为‘react hook 是真的好用啊’
const [ hook, sethook ] = useState('react hook 是真的好用啊');
const [ name ] = useState('baby张');
return (
<header className="UseEffect-header">
<h3>UseEffect</h3>
<Child hook={hook} name={name} />
{/**上面的变量和下面方法也是可以直接使用的 */}
<button onClick={() => sethook('我改变了react hook 的值' + new Date().getTime())}>改变hook</button>
</header>
);
};
const Child = (props) => {
const [ newhook, setnewhook ] = useState(props.hook);
//这样写可以代替以前的componentDidMount,第二个参数为空数组,表示该useEffect只执行一次
useEffect(() => {
console.log('first componentDidMount');
}, []);
//第二个参数,数组里是hook,当hook变化时,useEffect会触发,当hook变化时,先销毁再执行第一个函数。
useEffect(
() => {
setnewhook(props.hook + '222222222');
console.log('useEffect');
return () => {
console.log('componentWillUnmount ');
};
},
[ props.hook ]
);
//useLayoutEffect 强制useeffect的执行为同步,并且先执行useLayoutEffect内部的函数
useLayoutEffect(
() => {
console.log('useLayoutEffect');
return () => {
console.log('useLayoutEffect componentWillUnmount');
};
},
[ props.hook ]
);
return (
<div>
<p>{props.name}</p>
{newhook}
</div>
);
};
export default UseEffect;
Copy after login
3.useMemo & useCallback
They can both be used to optimize the rendering problem of sub-components, or listen to the state changes of sub-components to handle events. This is It was difficult to do in the past, because shouldComponentUpdate can monitor changes, but cannot control other external methods. It can only return true and false, and componentDidUpdate can only be executed after updating, so I want to do something before rendering. Things are not going to be easy.
useCallback is not available yet
import React, { useState, useMemo } from 'react';
const Child = ({ age, name, children }) => {
//在不用useMemo做处理的时候,只要父组件状态改变了,子组件都会渲染一次,用了useMemo可以监听某个状态name,当name变化时候执行useMemo里第一个函数
console.log(age, name, children, '11111111');
function namechange() {
console.log(age, name, children, '22222222');
return name + 'change';
}
{/** react 官网虽说useCallback与useMemo的功能差不多,但不知道版本问题还怎么回是,这个方法目前还不能用
const memoizedCallback = useCallback(
() => {
console.log('useCallback')
},
[name],
);
console.log(memoizedCallback,'memoizedCallback')
*/}
//useMemo有两个参数,和useEffect一样,第一个参数是函数,第二个参数是个数组,用来监听某个状态不变化
const changedname = useMemo(() => namechange(), [ name ]);
return (
<div style={{ border: '1px solid' }}>
<p>children:{children}</p>
<p>name:{name}</p>
<p>changed:{changedname}</p>
<p>age:{age}</p>
</div>
);
};
const UseMemo = () => {
//useState 设置名字和年龄,并用2两个按钮改变他们,传给Child组件
const [ name, setname ] = useState('baby张');
const [ age, setage ] = useState(18);
return (
<div>
<button
onClick={() => {
setname('baby张' + new Date().getTime());
}}
>
改名字
</button>
<button
onClick={() => {
setage('年龄' + new Date().getTime());
}}
>
改年龄
</button>
<p>
UseMemo {name}:{age}
</p>
<Child age={age} name={name}>
{name}的children
</Child>
</div>
);
};
export default UseMemo;
Copy after login
4.useRef
ref is almost the same as before, useRef is created - bound - used, three steps, Read the code and notes in detail
import React, { useState, useRef } from 'react';
const UseRef = () => {
//这里useState绑定个input,关联一个状态name
const [ name, setname ] = useState('baby张');
const refvalue = useRef(null);// 先创建一个空的useRef
function addRef() {
refvalue.current.value = name; //点击按钮时候给这个ref赋值
// refvalue.current = name //这样写时,即使ref没有绑定在dom上,值依然会存在创建的ref上,并且可以使用它
console.log(refvalue.current.value);
}
return (
<div>
<input
defaultValue={name}
onChange={(e) => {
setname(e.target.value);
}}
/>
<button onClick={addRef}>给下面插入名字</button>
<p>给我个UseRef名字:</p>
<input ref={refvalue} />
</div>
);
};
export default UseRef;
Copy after login
5.useContext
Friends who have used context before will understand it at a glance. UseContext is basically the same as the previous context usage. It’s almost the same. There are detailed comments in the code, creating, passing values, and using
import React, { useState, useContext, createContext } from 'react';
const ContextName = createContext();
//这里为了方便写博客,爷爷孙子组件都写在一个文件里,正常需要在爷爷组件和孙子组件挨个引入创建的Context
const UseContext = () => {
//这里useState创建一个状态,并按钮控制变化
const [ name, setname ] = useState('baby张');
return (
<div>
<h3>UseContext 爷爷</h3>
<button
onClick={() => {
setname('baby张' + new Date().getTime());
}}
>
改变名字
</button>
{/**这里跟context用法一样,需要provider向子组件传递value值,value不一定是一个参数 */}}
<ContextName.Provider value={{ name: name, age: 18 }}>
{/**需要用到变量的子组件一定要写在provider中间,才能实现共享 */}
<Child />
</ContextName.Provider>
</div>
);
};
const Child = () => {
//创建一个儿子组件,里面引入孙子组件
return (
<div style={{ border: '1px solid' }}>
Child 儿子
<ChildChild />
</div>
);
};
const ChildChild = () => {
//创建孙子组件,接受爷爷组件的状态,用useContext,获取到爷爷组件创建的ContextName的value值
let childname = useContext(ContextName);
return (
<div style={{ border: '1px solid' }}>
ChildChild 孙子
<p>
{childname.name}:{childname.age}
</p>
</div>
);
};
export default UseContext;
Copy after login
6.useReducer
The usereducer here will return state and dispatch, through The context is passed to the subcomponent, and then the state is directly called or the reducer is triggered. We often use useReducer together with useContext createContext to simulate the value transfer and reassignment operations of reudx.
import React, { useState, useReducer, useContext, createContext } from 'react';
//初始化stroe的类型、初始化值、创建reducer
const ADD_COUNTER = 'ADD_COUNTER';
const initReducer = {
count: 0
};
//正常的reducer编写
function reducer(state, action) {
switch (action.type) {
case ADD_COUNTER:
return { ...state, count: state.count + 1 };
default:
return state;
}
}
const CountContext = createContext();
//上面这一段,初始化state和reducer创建context,可以单独写一个文件,这里为了方便理解,放一个文件里写了
const UseReducer = () => {
const [ name, setname ] = useState('baby张');
//父组件里使用useReducer,第一个参数是reducer函数,第二个参数是state,返回的是state和dispash
const [ state, dispatch ] = useReducer(reducer, initReducer);
return (
<div>
UseReducer
{/* 在这里通过context,讲reducer和state传递给子组件*/}
<CountContext.Provider value={{ state, dispatch, name, setname }}>
<Child />
</CountContext.Provider>
</div>
);
};
const Child = () => {
//跟正常的接受context一样,接受父组件的值,通过事件等方式触发reducer,实现redux效果
const { state, dispatch, name, setname } = useContext(CountContext);
function handleclick(count) {
dispatch({ type: ADD_COUNTER, count: 17 });
setname(count % 2 == 0 ? 'babybrother' : 'baby张');
}
return (
<div>
<p>
{name}今年{state.count}岁
</p>
<button onClick={() => handleclick(state.count)}>长大了</button>
</div>
);
};
export default UseReducer;
Copy after login
[Related recommendations: Redis video tutorial]