In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly shows you "what is React Hook", the content is easy to understand, clear, hope to help you solve your doubts, the following let the editor lead you to study and learn this article "what is React Hook?"
React hook includes: useState, useEffect, useLayoutEffect, useMemo, useRef, useContext, useReducer, useDebugValue, useImperativeHandle and so on.
The operating environment of this tutorial: Windows7 system, react17.0.1 version, Dell G3 computer.
What is React Hook?
Here's what the React website says: Hook is a new feature in React 16.8. It allows you to use state and other React features without writing class.
Optionally, you can try Hook in some components without rewriting any existing code. But if you don't want to, you don't have to learn or use Hook now.
100% backward compatible Hook does not contain any destructive changes.
The available Hook is now released on v16.8.0.
There are no plans to remove class from React. You can read more about the progressive strategy of Hook in the chapter at the bottom of this page.
Hook does not affect your understanding of React concepts. On the contrary, Hook provides more direct API:props, state,context,refs, and lifecycle for known React concepts. As we'll see later, Hook also provides a more powerful way to combine them.
If you don't know enough about react, it is recommended to take a look at the official documents of react, write demo and then read the article, because there are some basic things of react that I will not go into detail.
React official document https://zh-hans.reactjs.org/docs/hooks-state.html
React provides Hookhook use useState to set and change state to replace the original state and setStateuseEffect instead of the original life cycle. The combined version of componentDidMount,componentDidUpdate and componentWillUnmount has the same function as useEffect, but it will synchronously call effectuseMemo to control component update conditions, which can be executed according to state change control method, optimize value transfer useCallbackuseMemo optimization, usecallback optimization transfer method, whether to update useRef is the same as the previous ref. Just more concise useContext context grandson and deeper components pass value useReducer to replace the original reducer in redux, use useDebugValue together with useContext to display custom hook tags in React developer tools for debugging. UseImperativeHandle allows you to customize the instance values that are exposed to the parent component when using ref.
1.useState
Import React from 'react';import'. / App.css' / / the usual way of writing class Change the state class App extends React.Component {constructor (props) {super (props) this.state = {hook:'react hook is really good changehook = () > {this.setState ({hook:' I changed the value of react hook'})} render () {const {hook} = this.state return ({hook}) Change hook)}} export {App} / / functional style Changing the state function App () {/ / creates a variable called hook The sethook method can change this variable with an initial value of 'react hook is really good' const [hook, sethook] = useState ("react hook is really good") Return ({hook} {/ * * the variables and methods here can also be used directly * /} sethook ("I changed the value of react hook")} > change hook);} export {App} / / arrow function, change the state export const App = props = > {const [hook, sethook] = useState ("react hook is really easy to use") Return ({hook} sethook ("I changed the value of react hook")} > change hook);}
The usage is noted in the demo above
After reading the comparative use of the above useState, a small demo structure is clearer, the code is more concise, more like writing js code, applied to the project, that is not happy.
2.useEffect & useLayoutEffect
UseEffect replaces the original lifecycle, the combined version of componentDidMount,componentDidUpdate and componentWillUnmount
UseEffect (() = > {return () = > {}}, [])
The first parameter is a function, which is triggered by default when it is rendered and updated for the first time. It comes with a return by default, and a function return indicates that something can be handled before it is destroyed.
The second parameter, array, is executed only once when empty, and is not triggered when it is updated. What is the parameter in it? useEffect will be executed only when the parameter changes.
UseEffect can be used many times and executed sequentially.
UseLayoutEffect forces the execution of useeffect to be synchronous, and executes functions within useLayoutEffect first
Import React, {useState, useEffect, useLayoutEffect} from 'react';// arrow function, change the state const UseEffect = (props) = > {/ / create a variable called hook, the sethook method can change this variable, the initial value is' react hook is really good 'const [hook, sethook] = useState (' react hook is really good'); const [name] = useState ('baby Zhang') Return (UseEffect {/ * * the variables above and the following methods can also be used directly * /} sethook ('I changed the value of react hook'+ new Date (). GetTime ()} > change hook) }; const Child = (props) = > {const [newhook, setnewhook] = useState (props.hook); / / this can be written instead of the previous componentDidMount, and the second parameter is an empty array, indicating that the useEffect is executed only once (() = > {console.log ('first componentDidMount');}, []) / / the second parameter is hook in the array. When hook changes, useEffect will trigger. When hook changes, destroy first and then execute the first function. UseEffect () = > {setnewhook (props.hook + '2222222222'); console.log ('useEffect'); return () = > {console.log (' componentWillUnmount');} }, [props.hook]); / / useLayoutEffect forces the execution of useeffect to be synchronous, and first executes the function inside useLayoutEffect useLayoutEffect (() = > {console.log ('useLayoutEffect')) Return () = > {console.log ('useLayoutEffect componentWillUnmount');};}, [props.hook]); return (
{props.name}
{newhook});}; export default UseEffect
3.useMemo & useCallback
They can all be used to optimize sub-component rendering problems, or listen for sub-component state changes to handle events, which was difficult in the past, because shouldComponentUpdate can monitor changes, but cannot control other external methods, and can only return true and false, while componentDidUpdate can only be executed after updates, so it is difficult to do something before rendering.
UseCallback is not available yet.
Import React, {useState, useMemo} from 'react';const Child = ({age, name, children}) = > {/ / when there is no useMemo processing, as long as the state of the parent component changes, the child component will render once. Using useMemo, you can listen to a certain state name and execute the first function console.log (age, name, children,' 11111111') in useMemo when name changes. Function namechange () {console.log (age, name, children, '22222222'); return name + 'change' } {/ * * react official website, although the function of useCallback is similar to that of useMemo, I don't know what the version problem is. At present, this method cannot use const memoizedCallback = useCallback (() = > {console.log ('useCallback')}, [name],) Console.log (memoizedCallback,'memoizedCallback') * /} / / useMemo has two parameters, like useEffect, the first parameter is a function, and the second parameter is an array, which is used to listen for a state that does not change const changedname = useMemo (() = > namechange (), [name]); return (
Children: {children}
Name: {name}
Changed: {changedname}
Age: {age}
);}; const UseMemo = () = > {/ / useState sets the name and age, and changes them with 2 buttons, passing them to the Child component const [name, setname] = useState ('baby Zhang'); const [age, setage] = useState (18) Return ({setname ('baby Zhang' + new Date (). GetTime ()) Change the name {setage ('age' + new Date (). GetTime ()) Change the age
UseMemo {name}: {age}
Children of {name});}; export default UseMemo
4.useRef
Ref is about the same as before, useRef creation-binding-use, three steps, look at the code and comments in detail
Import React, {useState, useRef} from 'react';const UseRef = () = > {/ / here useState binds an input and associates a state name const [name, setname] = useState (' baby Zhang'); const refvalue = useRef (null); / / create an empty useRef function addRef () {refvalue.current.value = name first / / assign the ref a value / / refvalue.current = name / / when you click the button, even if the ref is not bound to the dom, the value will still exist on the created ref, and you can use it console.log (refvalue.current.value) } return ({setname (e.target.value);}} / > insert the name below
Give me a UseRef name:
);}; export default UseRef
5.useContext
Friends who have used context before can understand at a glance. The words of useContext are similar to the basic usage of context before. There are detailed comments in the code, creating, passing values, and using.
Import React, {useState, useContext, createContext} from 'react';const ContextName = createContext (); / / in order to facilitate blogging, grandson components are all written in a file. Normally, you need to introduce the created Contextconst UseContext = () = () > {/ / here useState to create a state, and button to control the change const [name, setname] = useState (' baby Zhang'). Return (Grandpa UseContext {setname ('baby Zhang' + new Date (). GetTime ()) Change the name {/ * * here is the same as context, where provider is required to pass a value to the child component Value is not necessarily a parameter * /} {/ * * subcomponents that need variables must be written in the middle of provider in order to share * /}) }; const Child = () = > {/ / create a child component in which the grandchild component return (Child son) is introduced;} Const ChildChild = () = > {/ / create the grandchild component, accept the status of the grandparent component, and use useContext to get the value of the ContextName created by the grandchild component let childname = useContext (ContextName); return (grandson of ChildChild)
{childname.name}: {childname.age}
);}; export default UseContext
6.useReducer
The usereducer here returns state and dispatch, which is passed to the sub-component through context, and then directly calls state or triggers reducer. We often use useReducer with useContext createContext to simulate the value passing and reassignment operation of reudx.
Import React, {useState, useReducer, useContext, createContext} from 'react';// initializes the type of stroe, initializes the value, creates reducerconst ADD_COUNTER =' ADD_COUNTER';const initReducer = {count: 0}; / / normal reducer writes function reducer (state, action) {switch (action.type) {case ADD_COUNTER: return {... state, count: state.count + 1} Default: return state;}} const CountContext = createContext (); / / in the above paragraph, initialize state and reducer to create context, and you can write a separate file. For ease of understanding, const UseReducer = () > {const [name, setname] = useState ('baby Zhang') is written in a file. / / useReducer is used in the parent component. The first argument is the reducer function, the second argument is state, and the returns are state and dispash const [state, dispatch] = useReducer (reducer, initReducer). Return (UseReducer {/ * is passed here through context, reducer and state to subcomponents * /});} Const Child = () = > {/ / just like the normal accept context, accept the value of the parent component, trigger reducer through events, etc., to achieve the redux effect const {state, dispatch, name, setname} = useContext (CountContext); function handleclick (count) {dispatch ({type: ADD_COUNTER, count: 17}); setname (count% 2 = = 0? 'babybrother':' baby Zhang');} return (
{name} is {state.count} this year.
Handleclick (state.count)} > grown up); export default UseReducer; above is all the content of this article "what is React Hook?" Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.