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/02 Report--
This article is to share with you about the use of 10 kinds of Hook in React, the editor thinks it is very practical, so I share it with you to learn. I hope you can get something after reading this article.
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.
Completely optional 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
Hook currently provided by React
Hook uses 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 control components to update conditions, which can be executed according to the state change control method, optimize value transfer useCallbackuseMemo optimization, usecallback optimization transmission 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 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. The second parameter is an empty array, indicating that the useEffect only executes useEffect (() = > {console.log ('first componentDidMount');}, []); / / the second parameter is hook in the array. When the hook changes, the useEffect will trigger, and when the hook changes, destroy the first function first. UseEffect () = > {setnewhook (props.hook + '22222222'); console.log ('useEffect'); return () = > {console.log (' componentWillUnmount');};}, [props.hook]); / / useLayoutEffect forces the execution of useeffect to be synchronous, and first executes the function useLayoutEffect within 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 be used with 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 ());} > rename {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 still exists on the created ref, and you can use it to 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 (UseContext grandfather {setname ('baby Zhang' + new Date (). GetTime ());}} > change the name {/ * * here, like context, provider is required to pass the value to the subcomponent, and value is not necessarily a parameter * /}. The subcomponent that needs to use the variable must be written in the middle of the provider before it can be shared * /};} Const Child = () = > {/ / create a son component in which the grandchild component return (Child son) is introduced;}; const ChildChild = () = > create the grandchild component, accept the status of the grandchild component, and use useContext to get the value let childname = useContext (ContextName) of the ContextName created by the grandchild component; 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 state and dispash const [state, dispatch] = useReducer (reducer, initReducer) are returned. Return (UseReducer {/ * here passes reducer and state to child components * /});}; const Child = () = > {/ / as normally accepts context, accepts the value of the parent component, triggers 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
Attach github address 10 hook demo points a little star
These are 10 ways to use Hook in React. The editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please 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.