简体   繁体   中英

How do you properly call useState within a React custom Hook?

I'm trying to create a custom Hook that allows me to pass a value and subtract 1 whenever I press a button. I'm currently getting the error that says

React Hook "useLastPage" is called in function "handleLastPage" which is neither a React function component or a custom React Hook function

in the following code:

function usePrevPage (page) {
    const [lastPage, useLastPage] = useState(page)
    useEffect(() => {
        function handleLastPage(page) {
            useLastPage(page - 1)
        }
        handleLastPage()
    })
    return lastPage
}

My code mirrors the React Doc's custom hook example closely so I'm not sure how to call useLastPage within my custom Hook. Following is the example from React's Doc :

function useFriendStatus(friendID) {
  const [isOnline, setIsOnline] = useState(null);

  useEffect(() => {
    function handleStatusChange(status) {
      setIsOnline(status.isOnline);
    }

    ChatAPI.subscribeToFriendStatus(friendID, handleStatusChange);
    return () => {
      ChatAPI.unsubscribeFromFriendStatus(friendID, handleStatusChange);
    };
  });

  return isOnline;
}

React is confused as you are using useLastPage for the updator of const [lastPage, useLastPage] = useState(page) .

Try to change useLastPage to setLastPage . You should use use prefix for hooks.

Check out the demo - https://codesandbox.io/s/crazy-neumann-hgely

useEffect is similar to componentDidMount and componentDidUpdate . It will run when the Component is being mounted/updated . To decrease the lastPage state value you can simply call its setter directly inside the useState callback. Also I suggest changing the setter prefix to set instead of use

function usePrevPage (page) {
    const [lastPage, setLastPage] = useState(page);
    useEffect(() => {
          setLastPage(page-1);
    });
    return lastPage;
}

If you want to change the value on button click then you need to write the handler outside useEffect and set that to the button's onClick prop.

I think that your main problem is that you are calling your set function useLastPage - The React linter looks for functions that begin with the word use and tries to 'lint' them as hooks. In this case useLastPage isn't a hook, it's the returned setter from useState . I suspect that if you call it setLastPage that will clear up the error message for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM