Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
July 27, 2022 09:31 am GMT

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 dont work inside a class component, only in a function component.

Making unique hooks should be prioritized 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 that is connected to the state and lifecycle of the program.

The goal of a custom hook is to create a function that you can quickly reuse in different area 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])

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} }

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.


Original Link: https://dev.to/vokespeaks/what-exactly-do-reactreact-native-custom-hooks-do-40pe

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To