Home > OS >  Array after a function
Array after a function

Time:12-21

Hello im new in react sometimes i find there are array after a function, I tried to find the use of it, can explain the use of it or provide a link for the documentation for will be helpful. Thank you

This is the example of the code

export const PostsList = () => {  
    const {
      data: posts = [],
      isLoading,
      isSuccess,
      isError,
      error
    } = useGetPostsQuery()
    
    const sortedPosts = useMemo(() => {
    const sortedPosts = posts.slice()
    sortedPosts.sort((a, b) => b.date.localeCompare(a.date))

    return sortedPosts
    
  }, [posts])}


I dont know the use of [posts] at the end of the code

CodePudding user response:

Formatting your code better will make it clearer what the array is actually used for:

    const sortedPosts = useMemo(() => {
        const sortedPosts = posts.slice()
        sortedPosts.sort((a, b) => b.date.localeCompare(a.date))
        return sortedPosts
    }, [posts])
}

The array is used as a parameter to useMemo, a React hook.

Many React hooks (functions that start with use) make use of such an array. These are called "dependency arrays." Generally, what the array means is:

  • Whenever one of the items in the array changes render-to-render, re-calculate the value inside, and use the new value
  • If all of the items in the array stay the same during a new render, return the item calculated during the last render

In this case, with useMemo, it means that the sortedPosts will only be re-calculated when the posts changes. If there's a re-render when posts doesn't change, the value returned by the previous render's useMemo will be used for sortedPosts instead.

Re-using the old value instead of calculating and using the value anew on each render improves performance, because it means that when the value is passed down to other components, they won't have to re-render if the value is the same (=== to the value from the past render).

Look at React's documentation for hooks for details on what the array does for each different hook.

  • Related