In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article is about what Hooks is in React. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.
What is Hooks?
Hooks is translated into hooks, and Hooks is the function in the function component that is responsible for hooking into external functions.
React provides some common hooks, and React also supports custom hooks, which are used to introduce external functionality to functions.
When we need to introduce external functionality in the component, we can use the hooks provided by React, or custom hooks.
For example, if you introduce a manageable state function into a component, you can use the useState function, and the use of useState is described in more detail below.
Why use Hooks?
There are two main reasons for using Hooks:
Simplified logic reuse
Make complex components easier to understand.
1. Simplified logic reuse
Before the emergence of Hooks, React had to borrow high-level components, render props and other complex design patterns to achieve logic reuse, but high-level components will produce redundant component nodes, making debugging more complex.
Hooks allows us to reuse state logic without modifying the component structure, and the use of custom Hooks is described in more detail below.
two。 Make complex components easier to understand
In the class component, the code of the same business logic is scattered in different life cycle functions of the component, while Hooks can aggregate the code for the same business logic together, so that the business logic is clearly separated and the code is easier to understand and maintain.
4. Commonly used Hooks1. UseState
UseState is a Hook that allows you to add state to the React function component.
Examples of use are as follows:
Import React, {useState} from 'react';function Example () {/ / declare a state variable called "count" const [count, setCount] = useState (0); / /.
The above code declares a state variable count with an initial value of 0 and updates the current count by calling setCount.
2. UseEffect
UseEffect allows you to perform side effects in function components.
Side effects refer to a piece of code that has nothing to do with the result of the current execution, such as data acquisition, setting subscriptions, and manually changing the DOM in the React component.
UseEffect can receive two parameters. The code is as follows:
UseEffect (callback, dependencies)
The first argument is the function callback to execute, and the second argument is the optional dependency array dependencies.
The dependency is optional, and if not specified, callback executes each time the function component completes execution; if so, it executes only if the value in the dependency changes.
Examples of use are as follows:
Function Example () {const [count, setCount] = useState (0); / / Similar to componentDidMount and componentDidUpdate: useEffect (()) = > {/ / Update the document title using the browser API document.title = `You clicked ${count} times`; return () = > {/ / can be used for cleanup, equivalent to componentWillUnmount}} of class components, [count]); / / specify the dependency as count, and execute this side effect / when count updates.
The above code implements the execution of the side effect function when the dependency count is updated through useEffect, and clears the result of the previous execution by returning the callback function.
In addition, useEffect provides four opportunities to perform side effects:
Execute after each render: no second dependency parameter is provided. For example, useEffect (() = > {})
Execute only after the first render: provide an empty array as a dependency. For example, useEffect (() = > {}, [])
Executed for the first time and after a dependency change: provides an array of dependencies. For example, useEffect (() = > {}, [deps])
Component unmount executes: returns a callback function. For example, useEffect () = > {return () = > {}}, []).
3. UseCallback
The callback function defined by useCallback only redeclares the callback function when the dependency changes, thus ensuring that the component does not create duplicate callback functions. Components that receive this callback function as properties do not need to be re-rendered frequently.
Examples of use are as follows:
Const memoizedCallback = useCallback (() = > {doSomething (a, b)}, [a, b])
The above code redeclares the callback function only when the dependencies an and b change.
4. UseMemo
The creation function defined by useMemo is recalculated only when a dependency changes, which facilitates high-overhead calculations that are not repeated each time you render, and components that receive this calculated value as properties do not need to re-render frequently.
Examples of use are as follows:
Const memoizedValue = useMemo (() = > computeExpensiveValue (a, b), [a, b])
The above code is recalculated only when the dependencies an and b change.
5. UseRef
UseRef returns a ref object that persists throughout the lifecycle of the component.
He has two uses:
Save a reference to the DOM node
Share data between multiple renderings.
Examples of the introduction of saving DOM nodes are as follows:
Function TextInputWithFocusButton () {const inputEl = useRef (null) const onButtonClick = () = > {/ / `current` points to the text input element inputEl.current.focus ()} return (Focus the input)} that has been mounted on the DOM
The above code creates the ref object through useRef, saves the reference to the DOM node, and can DOM the ref.current.
Examples of sharing data between multiple renderings are as follows:
Import React, {useState, useCallback, useRef} from 'react'export default function Timer () {/ / define the cumulative time const used by time state to save timing [time SetTime] = useState (0) / / defines timer as a container for saving a variable const timer = useRef (null) / / event handler function to start timing between cross-component renderings const handleStart = useCallback (() = > {/ / use the current property to set the value of ref timer.current = window.setInterval () = > {setTime ((time) = > time + 1)}, 100)} []) / / pause the event handler function const handlePause = useCallback (()) > {/ / use clearInterval to stop timing window.clearInterval (timer.current) timer.current = null}, []) return ({time / 10} seconds. Start Pause)}
The above code creates a ref object called timer through useRef, which can be called during cross-component rendering, create a new timer at the start of the timer, and empty the timer when the timing is paused.
6. UseContext
UseContext is used to receive a context object and return the value of the context, which enables data sharing across levels.
Examples are as follows:
/ / create a context object const MyContext = React.createContext (initialValue) function App () {return (/ / pass the value of context through Context.Provider)} function Container () {return} function Test () {/ / get the value of Context const theme = useContext (MyContext) / / 1 return}
The above code obtains the Context defined in the App component through useContext, and achieves the data sharing across hierarchical components.
7. UseReducer
UseReducer is used to introduce Reducer functionality.
Examples are as follows:
Const [state, dispatch] = useReducer (reducer, initialState)
It takes the initial values of the Reducer function and state as arguments and returns an array. The first member of the array is the current value of the state, and the second member is the dispatch function that sends action.
5. Custom Hooks
By customizing the Hooks, you can extract component logic into reusable functions.
1. How do I create a custom Hooks?
A custom Hooks is a function, which has two characteristics that distinguish it from a normal function:
The name begins with "use"
Other Hook is called inside the function.
Examples are as follows:
Import {useState, useCallback} from 'react'function useCounter () {/ / define count this state is used to save the current value const [count, setCount] = useState (0) / / to implement the operation of adding 1 const increment = useCallback (() = > setCount (count + 1), [count]) / / the operation of minus 1 const decrement = useCallback (() = > setCount (count-1)) [count]) / / reset counter const reset = useCallback (() = > setCount (0), []) / / send the operation export of business logic out for callers to use return {count, increment, decrement, reset}} / / component 1function MyComponent1 () {const {count, increment, decrement, reset} = useCounter () / component 2function MyComponent2 () {const {count, increment, decrement, reset} = useCounter ()}
The above code easily reuses business logic between MyComponent1 components and MyComponent2 components by customizing Hooks useCounter.
two。 Custom Hooks Library-react-use
React officially provides the react-use library, which encapsulates a large number of custom Hooks that can be used directly, which helps us to simplify the internal logic of the component and improve the readability and maintainability of the code.
Among them, the custom Hooks we often use are:
UseLocation and useSearchParam: track the location status of the page navigation bar
UseScroll: tracks the scrolling position of the HTML element
UseScrolling: tracks whether the HTML element is scrolling
UseAsync, useAsyncFn, and useAsyncRetry: parsing an async function
UseTitle: sets the title of the page.
Thank you for reading! This is the end of this article on "what is Hooks in React?". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!
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.