SoFunction
Updated on 2025-04-07

How to custom hooks in React

  • What is hook

HookyesReact 16.8New features. It is usually used simultaneously with functional components. Can make functional components not writtenclassIn the case ofclassComponent status, life cycle, reference and other functions.

  • What are the hooks commonly used

ReactCommonly used inhookshave:

  • useStateStatus Management
  • useEffectlife cycle
  • useContextCross-component data delivery
  • useRefComponent references
  • ....
  • Custom hook

CustomizehookIn fact, it is just a custom function, which is very similar to when we write function components. CustomhookComponent naming and systemhooksLikewise, it needs tousebeginning. Let's usereact+tsLet's introduce some commonly used customizationshook

  • Get the window width and height change

Achieve the goal: ByuseWindowSize()Get the width and height of the window in real time

Create a new hook file, the code is as follows:

import { useEffect, useState } from "react";

//Define the size objectinterface WindowSize {
    width: number,
    height: number
}
const useWindowSize = () => {
    const [size, setSize] = useState<WindowSize>({
        width: ,
        height: 
    })

    useEffect(() => {
        // Listen to size changes        ('resize', () => {
            setSize({
                width: ,
                height: 
            })
        })
        return () => {
            //Remove listening when component is destroyed            ('resize', () => {
                setSize({
                    width: ,
                    height: 
                })
            })
        }
    },[])
    return size
}
export default useWindowSize

Used in the component as follows:

import useWindowSize from './hooks/useWindowSize';
function App() {
  const size = useWindowSize()
  return (
    <div>
      <div>Page width:{}</div>
      <div>Page height:{}</div>
    </div>
  )
}
export default App

Drag the browser to zoom in and out, and the data on the page can change dynamically

  • Get the scroll offset change

Goal: ByuseWindowScroll()Get the scroll offset of the page in real time

Create a new hook file, the code is as follows:

import { useEffect, useState } from "react"

//Define the offset objectinterface ScrollOffset {
    x: number,
    y: number
}

const useWindowScroll = () => {
    const [off, setOff] = useState<ScrollOffset>({
        x: , 
        y: 
    })
    useEffect(() => {
        //monitor        ('scroll', () => {
            setOff({
                x: ,
                y: 
            })
        })
        return () => {
            //Remove the listening            ('scroll', () => {
                setOff({
                    x: ,
                    y: 
                })
            })
        }
    })
    return off
}
export default useWindowScroll

Used in the component as follows:

import useWindowScroll from './hooks/useWindowScroll';
function App() {
  const offSet = useWindowScroll()

  return (
    <div style={{height: '10000px', width: '10000px'}}>
      <div>scrolly:{}</div>
      <div>scrollx:{}</div>
    </div>
  )
}

export default App
  • Automatically synchronize to localStorage

Goal: Byconst [value, setValue] = useLocalStorage('key', 'value') The default initial value and key can be passed in, and the value can be automatically synchronized to localStorage every time you modify the value.

Create a new hook classuseLocalStorage, the code is as follows:

import { useEffect, useState } from "react"

const useLocalStorage = (key: string, defaultValue: string) : ([string, <<string>>]) => {
    const [value, setValue] = useState(defaultValue)
    useEffect(() => {
        (key, value)
    },[key, value])
    return [value, setValue]
}

export default useLocalStorage

Used in components:

import useLocalStorage from './hooks/useLocalStorage';

function App() {

  const [value, setValue] = useLocalStorage('key', 'react')

  return (
    &lt;div&gt;

    &lt;button onClick={() =&gt; {
        //Click to modify the value and it will automatically be synchronized to the local area        setValue('vue')
      }}&gt;Click&lt;/button&gt;
      &lt;div&gt;{ value }&lt;/div&gt;
    &lt;/div&gt;
  )
}
export default App

This is all about this article about React custom hooks. For more related React custom hook content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!