Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

React Hooks

React Hooks

React Hooks are an important feature introduced in React 16.8 that enable function components to have some features of class components, such as state management and the use of lifecycle methods.

With Hooks, you can write React components more concisely and flexibly.

1. What are React Hooks?

React Hooks are an enhancement mechanism for function components that let you use React features without writing class components. The main Hooks include useState, useEffect, useContext, useReducer, useCallback, useMemo, useRef, and LinkedHashMap, among others. useImperativeHandle , etc. These Hooks provide ways to access React features, allowing you to better organize and reuse your code.

2. Main React Hooks

useState

useState The Hook allows you to use local state in a function component. It returns a state value and a function to update that value.

Example

import

React

,

{

useState

}

from

'react'

;

function

Counter

(

)

{

 

const

[

count

,

setCount

]

=

useState

(

0

)

;

 

return

(

   

<

div

<

p

You clicked

{

count

}

times

p

     

<

button onClick

=

{

(

)

=>

setCount

(

count

1

)

}

Click me

button

   

div

 

)

;

}

useEffect

useEffect The Hook allows you to perform side effects in a function component (such as data fetching, subscription management, DOM operations, etc.). It runs after every render.

Example

import

React

,

{

useState

,

useEffect

}

from

'react'

;

function

Timer

(

)

{

 

const

[

seconds

,

setSeconds

]

=

useState

(

0

)

;

  useEffect

(

(

)

=>

{

   

const

interval

=

setInterval

(

(

)

=>

{

      setSeconds

(

seconds

=>

seconds

1

)

;

   

}

,

1000

)

;

   

return

(

)

=>

clearInterval

(

interval

)

;

 

}

,

[

]

)

;

// An empty array as the second parameter means it runs only on mount and unmount

 

return

<

p

Timer

:

{

seconds

}

seconds

p

;

}

The following are some of the main React Hooks and their uses:

**useState **- used to add state in function components, you can use it to track data that changes over time.



const [state, setState] = useState(initialState);

useEffect - used to perform side effects, such as data fetching, subscriptions, or manually changing the DOM; it is similar to the componentDidMount, componentDidUpdate, and componentWillUnmount lifecycles in class components.

useEffect(() => {

  // Execute side effects

  return () => {

    // Cleanup operation

  };

}, [dependencies]); // 依赖数组

useContext - used to access data passed through React context in the component tree without passing props through every component.

const value = useContext(MyContext);

useReducer - used for more complex state logic; it takes a reducer function and an initial state, then returns the current state and a dispatch function for dispatching actions.

const [state, dispatch] = useReducer(reducer, initialState);

useCallback - used to return a memoized version of a callback function, preventing unnecessary renders.

const memoizedCallback = useCallback(

  () => {

    // Callback function body

  },

  [dependencies] // 依赖数组

);

useMemo - used to memoize computation results, avoiding repeated calculation on every render.



const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);

useRef - used to create a reference to a DOM element or value that can persist between renders.



const refContainer = useRef(initialValue);

useImperativeHandle - used to expose methods of DOM elements when using ref.

useImperativeHandle(ref, () => ({

  // Exposed methods

}));

useLayoutEffect - 与 useEffect 类似,但它在所有的 DOM 变更之后同步执行。这在需要读取 DOM 布局并同步触发重渲染时非常有用。



useLayoutEffect(() => {

  // Side effect operation

}, [dependencies]);

useDebugValue - used to display a label for a custom hook in React Developer Tools.



useDebugValue(value);

3. Benefits of using React Hooks

4. Notes

5. Example

The following is an example using multiple React Hooks:

Example

import

React

,

{

useState

,

useEffect

}

from

'react'

;

function

Example

(

)

{

 

const

[

count

,

setCount

]

=

useState

(

0

)

;

  useEffect

(

(

)

=>

{

    document.

title

=

`You clicked $

{

count

}

times`

;

 

}

,

[

count

]

)

;

// Update the title only when count changes

 

return

(

   

<

div

<

p

You clicked

{

count

}

times

p

     

<

button onClick

=

{

(

)

=>

setCount

(

count

1

)

}

Click me

button

   

div

 

)

;

}

export

default

Example

;

In the code above, we used useState to manage the state of count, useEffect to update the page title, and a simple button to increase count.

With Hooks, you can write more concise and reusable component code.

Hooks also make testing component logic easier, because you can test each hook's logic individually without wrapping it in a component.

In addition, Hooks support customization; you can write your own Hooks to encapsulate complex logic and then reuse them across multiple components.