DEV Community

Voke Efe
Voke Efe

Posted on

What exactly do React/React Native Custom Hooks do?

A hook

Hooks are functions that let you โ€œhook intoโ€ React state and lifecycle features from function components. Hooks donโ€™t work inside a class component, only in a function component.

Making unique hooks should be prioritsed over repetitive coding and adhering to recommended practices.

One of the cool things about React is the use of reusable components and this is not limited to JSX components in React, functions themselves are reusable. When creating an application, you will frequently execute data retrieval connected to the program's state and lifecycle.

The goal of a custom hook is to create a function that you can quickly reuse in different areas of your application to avoid DRY code and improve your application performance and efficiency.

You have an application with the Home and Profile screens. The user data must appear on both screens. You create the API call in the Home Screen and duplicate it on the Profile Screen in order to display the user data on both displays. If a user navigates to either screen, data is being fetched, which is OK because you successfully retrieve your data from the API and represent the data on each panel.

const getUserProfile = useCallback(() => {
    // API call logic
}, [])

useEffect(() => {
    getUserProfile()
}, [getUserProfile])
Enter fullscreen mode Exit fullscreen mode

Making the API call function into a hook that can be called from the Home and Profile is a simple solution and recommended practice. This will decrease DRY code and enhance the efficiency of your application.

export const useGetUserProfile = () => {

const [userProfile, setUserProfile] = useState() 

    const getUserProfile = useCallback(() => {
        // API call logic
    })

    useEffect(() => {
        getUserProfile()
    }, [getUserProfile])

return {userProfile} 
}
Enter fullscreen mode Exit fullscreen mode

Custom hooks are functions but not all functions can be referred to as a hook, below are what makes a function a hook:

  • It must be named starting with the word use.
  • It must be named in the camel case.

Start developing your own custom hooks because hooks in React can solve a wide range of issues that seem unconnected.

Top comments (0)