Home  >  Article  >  Web Front-end  >  What are react hooks?

What are react hooks?

青灯夜游
青灯夜游Original
2022-03-21 18:58:447959browse

There are 10 react hooks: 1. useState, used to set and change state; 2. useMemo, used to control component update conditions; 3. useContext, used to pass values ​​​​to components; 4. useDebugValue, display since Define labels; 5. useCallback and so on.

What are react hooks?

The operating environment of this tutorial: Windows7 system, react17.0.1 version, Dell G3 computer.

What is React Hook?

The React official website introduces it this way: Hook is a new feature of React 16.8. It allows you to use state and other React features without writing classes.

  • Completely optionalYou can try Hooks in some components without rewriting any existing code. But you don’t have to learn or use Hooks right now if you don’t want to.

  • 100% backwards compatible Hook contains no breaking changes.

  • Available now Hook has been released in v16.8.0.

  • There are no plans to remove classes from ReactYou can read more about the progressive strategy for Hooks in the section at the bottom of this page.

  • Hook will not affect your understanding of React conceptsOn the contrary, Hook provides a more direct API for known React concepts: props, state, context , refs and lifecycle. As we will see later, Hooks also provide a more powerful way to combine them.


If you don’t know enough about react, it is recommended to read the official react documentation first, write a demo and then read the article, because I will briefly mention some basic things about react without going into details.
react official documentation https://zh-hans.reactjs.org/docs/hooks-state.html

Hooks provided by React

##useStateSet and change state, replacing the original state and setStateuseEffectInstead of the original life cycle, the merged version of componentDidMount, componentDidUpdate and componentWillUnmount##useLayoutEffectuseMemouseCallbackuseRefuseContextuseReduceruseDebugValueuseImperativeHandle

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>
  );
};

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 &#39;react&#39;;

//箭头函数的写法,改变状态
const UseEffect = (props) => {
	//创建了一个叫hook的变量,sethook方法可以改变这个变量,初始值为‘react hook 是真的好用啊’
	const [ hook, sethook ] = useState(&#39;react hook 是真的好用啊&#39;);
	const [ name ] = useState(&#39;baby张&#39;);
	return (
		<header className="UseEffect-header">
			<h3>UseEffect</h3>
			<Child hook={hook} name={name} />
			{/**上面的变量和下面方法也是可以直接使用的 */}
			<button onClick={() => sethook(&#39;我改变了react hook 的值&#39; + new Date().getTime())}>改变hook</button>
		</header>
	);
};

const Child = (props) => {
	const [ newhook, setnewhook ] = useState(props.hook);
	//这样写可以代替以前的componentDidMount,第二个参数为空数组,表示该useEffect只执行一次
	useEffect(() => {
		console.log(&#39;first componentDidMount&#39;);
	}, []);

	//第二个参数,数组里是hook,当hook变化时,useEffect会触发,当hook变化时,先销毁再执行第一个函数。
	useEffect(
		() => {
			setnewhook(props.hook + &#39;222222222&#39;);
			console.log(&#39;useEffect&#39;);
			return () => {
				console.log(&#39;componentWillUnmount &#39;);
			};
		},
		[ props.hook ]
	);

	//useLayoutEffect 强制useeffect的执行为同步,并且先执行useLayoutEffect内部的函数
	useLayoutEffect(
		() => {
			console.log(&#39;useLayoutEffect&#39;);
			return () => {
				console.log(&#39;useLayoutEffect componentWillUnmount&#39;);
			};
		},
		[ props.hook ]
	);

	return (
		<div>
			<p>{props.name}</p>
			{newhook}
		</div>
	);
};

export default UseEffect;

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 &#39;react&#39;;

const Child = ({ age, name, children }) => {
    //在不用useMemo做处理的时候,只要父组件状态改变了,子组件都会渲染一次,用了useMemo可以监听某个状态name,当name变化时候执行useMemo里第一个函数
    console.log(age, name, children, &#39;11111111&#39;);
	function namechange() {
		console.log(age, name, children, &#39;22222222&#39;);
		return name + &#39;change&#39;;
    }
     {/** react 官网虽说useCallback与useMemo的功能差不多,但不知道版本问题还怎么回是,这个方法目前还不能用
    const memoizedCallback = useCallback(
        () => {
            console.log(&#39;useCallback&#39;)
        },
        [name],
      );
    console.log(memoizedCallback,&#39;memoizedCallback&#39;)
     */}
    //useMemo有两个参数,和useEffect一样,第一个参数是函数,第二个参数是个数组,用来监听某个状态不变化
	const changedname = useMemo(() => namechange(), [ name ]);
	return (
		<div style={{ border: &#39;1px solid&#39; }}>
			<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(&#39;baby张&#39;); 
	const [ age, setage ] = useState(18);
	return (
		<div>
			<button
				onClick={() => {
					setname(&#39;baby张&#39; + new Date().getTime()); 
				}}
			>
				改名字
			</button>
			<button
				onClick={() => {
					setage(&#39;年龄&#39; + new Date().getTime());
				}}
			>
				改年龄
			</button>
			<p>
				UseMemo {name}:{age}
			</p>
			<Child age={age} name={name}>
				{name}的children
			</Child>
		</div>
	);
};

export default UseMemo;

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 &#39;react&#39;;

const UseRef = () => {
	//这里useState绑定个input,关联一个状态name
	const [ name, setname ] = useState(&#39;baby张&#39;);
	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;

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 &#39;react&#39;;

const ContextName = createContext();
//这里为了方便写博客,爷爷孙子组件都写在一个文件里,正常需要在爷爷组件和孙子组件挨个引入创建的Context

const UseContext = () => {
	//这里useState创建一个状态,并按钮控制变化
	const [ name, setname ] = useState(&#39;baby张&#39;);
	return (
		<div>
			<h3>UseContext 爷爷</h3>
			<button
				onClick={() => {
					setname(&#39;baby张&#39; + 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: &#39;1px solid&#39; }}>
			Child 儿子
			<ChildChild />
		</div>
	);
};

const ChildChild = () => {
	//创建孙子组件,接受爷爷组件的状态,用useContext,获取到爷爷组件创建的ContextName的value值
	let childname = useContext(ContextName);
	return (
		<div style={{ border: &#39;1px solid&#39; }}>
			ChildChild 孙子
			<p>
				{childname.name}:{childname.age}
			</p>
		</div>
	);
};

export default UseContext;

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 &#39;react&#39;;

//初始化stroe的类型、初始化值、创建reducer
const ADD_COUNTER = &#39;ADD_COUNTER&#39;;
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(&#39;baby张&#39;);
	//父组件里使用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 ? &#39;babybrother&#39; : &#39;baby张&#39;);
	}
	return (
		<div>
			<p>
				{name}今年{state.count}岁
			</p>
			<button onClick={() => handleclick(state.count)}>长大了</button>
		</div>
	);
};

export default UseReducer;

[Related recommendations: Redis video tutorial]

hook Purpose
has the same effect as useEffect , but it will call effect synchronously
Control component update conditions, control method execution and optimize value transfer based on state changes
useMemo optimizes the value transfer, usecallback optimizes the transfer method, whether to update
Same as the previous ref, It’s just more concise
Context and deeper components pass values
Instead of the reducer in the original redux, use
with useContext to display the custom hook label in the React developer tools for debugging.
allows you to customize the instance value exposed to the parent component when using ref.

The above is the detailed content of What are react hooks?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn