React custom hook
🪝

React custom hook

Author
Tags
React.js
JavaScript
Slug
react-custom-hooks
Published
Sep 27, 2023
Tag
// useFetch.js
import { useState, useEffect } from 'react'

const useFetch = (url) => {
    const [data, setData] = useState(null)
    const fetchData = async () => {
        const response = await fetch(url)
        const json = await response.json()
        setData(json)
    }

    useEffect(() => {
        fetchData()
    }, [url])

    return [data, setData
}

export default useFetch
 
// component.jsx
import useFetch from '../hooks/useFetch'

export default function Component() {
    const [data, setData] = useFetch('https://jsonplaceholder.typicode.com/users')
    return (
        <div>
            {JSON.stringify(data)}
        </div>
    )
}