Hook
Hook is a new feature of React 16.8.0.
Hook allows you to use more React features without classes. Hook cannot be used in class components.
Rules of Use:
- Hook can only be called at the outermost level of a function. Do not call in loops, conditional judgements, or subfunctions.
- Hook can only be invoked in React's function components. Don't call it in other JavaScript functions.
State Hook
useState
useState can be used in function components without class components, and multiple state s can be declared by multiple calls.
- Parameters:
The only parameter in the useState() method is the initial state.
- Return value:
The current state and the function that updates the state.
Functional updates:
If the new state needs to be calculated using the previous state, then the function can be passed to setState. This function receives the previous state and returns an updated value.
function Counter({initialCount}) { const [count, setCount] = useState(initialCount); return ( <> Count: {count} <button onClick={() => setCount(initialCount)}>Reset</button> <button onClick={() => setCount(prevCount => prevCount + 1)}>+</button> <button onClick={() => setCount(prevCount => prevCount - 1)}>-</button> </> ); }
Effect Hook
Effect Hook lets you perform side effects in function components (data acquisition, subscription, or manual modification of DOM in React components). We call these operations "side effects" or "effects" for short.
useEffect
Use Effect Hook can be regarded as a combination of three functions: component DidMount, component DidUpdate and component WillUnmount.
useEffect is executed after each rendering (after the first rendering and after each update), and if your effect returns a function, React will call it when the component is unloaded to perform a cleanup operation.
useEffect can be called multiple times within a component. Hook allows us to separate them according to the purpose of the code. React calls each effect in the component in turn in the order of the effect declaration.
Use location:
UseEffect is called inside the component. Placing useEffect inside the component allows us to directly access count state variables (or other props) in effect.
Performance optimization:
The second optional parameter of useEffect enables you to notify React to skip the call to effect if certain values do not change between two renderings. Make sure that the array contains all variables that change over time in the external scope and are used in the effect
// Update only when count changes useEffect(() => { document.title = `You clicked ${count} times`; }, [count]);
The sample code details useState and useEffect:
// Introduce useState Hook in React. It lets us store internal state in function components // Introducing useEffect import React, { useState, useEffect } from 'react'; function Example(props) { // Declare a state variable called count and set it to 0 const [count, setCount] = useState(0); // Declare the second state const [isOnline, setIsOnline] = useState(null); // effect without Clearance useEffect(() => { // Set the title of the document to include the number of clicks. document.title = `You clicked ${count} times`; }); // effect to be cleared useEffect(() => { function handleFn(val) { setIsOnline(val); } // Registered Monitoring XXAPI.subscribe(handleFn); // Clear up listening return () => { XXAPI.unsubscribe(handleFn); }; }); return ( <div> // Read State: We can use count directly <p>You clicked {count} times</p> // Update State: You can update the current count by calling setCount <button onClick={() => setCount(count + 1)}> Click me </button> </div> ); }
useLayoutEffect
Its function signature is the same as useEffect, but it calls effect synchronously after all DOM changes. It can be used to read the DOM layout and trigger the rendering synchronously. The update plan inside useLayoutEffect will be refreshed synchronously before the browser performs rendering. Use standard useEffect whenever possible to avoid blocking visual updates.
Unlike component DidMount or component DidUpdate, the effect scheduled with useEffect does not block the browser's update screen, which makes your application seem more responsive. In most cases, effect does not need to be executed synchronously. In individual cases (such as measuring layout), the use Layout Effect is needed.
useRef
useRef returns a mutable ref object whose. current property is initialized as an incoming parameter (initial Value). The ref object returned remains unchanged throughout the life cycle of the component.
function TextInputWithFocusButton() { const inputEl = useRef(null); const onButtonClick = () => { // ` Curr `Points to the text input element that has been mounted on the DOM inputEl.current.focus(); }; return ( <> <input ref={inputEl} type="text" /> <button onClick={onButtonClick}>Focus the input</button> </> ); }
useRef() is more useful than the ref attribute. It can easily save any variable value, similar to the way instance fields are used in class es. useRef will not notify you when the ref object content changes. Changing the. current property does not trigger component re-rendering.
Custom Hook
Custom Hook is a function whose name begins with use (which must begin with use), and other Hoks can be called within the function. Custom Hook is used to extract shared logic between multiple components and can be used to replace render props and HOC.
Calling within a component that needs shared logic is simple, just introduce a defined custom Hook and pass in the parameters you want to get the return value you want to act on the current component.
The following examples are given:
- Extract custom Hook:
import React, { useState, useEffect } from 'react'; function useFriendStatus(friendID) { const [isOnline, setIsOnline] = useState(null); useEffect(() => { function handleStatusChange(status) { setIsOnline(status.isOnline); } ChatAPI.subscribeToFriendStatus(friendID, handleStatusChange); return () => { ChatAPI.unsubscribeFromFriendStatus(friendID, handleStatusChange); }; }); return isOnline; }
- Use custom Hook:
function FriendListItem(props) { const isOnline = useFriendStatus(props.friend.id); return ( <li style={{ color: isOnline ? 'green' : 'black' }}> {props.friend.name} </li> ); }
Original git address If it's helpful, star t and keep updating.