0

Can I use useRef() for the purpose to memoize an object from a custom hook? Because without that when if I use that returned object from the hook as a useEffect dependency I get an infinity loop of requests.

Example of my code that I use now:

  const apiHook = useRef({})
  apiHook.current = useRequest(
    'http://someapi',
    {
      onSuccess: (data) => {
        console.log(data)
      }
    }
  )
  useEffect(() => {
    apiHook.current.run()
  }, [])
4

2 Answers 2

2

You probably want something like

function Component() {
  const apiResp = useRequest('http://someapi');
  useEffect(() => {
    console.log(`New data: ${apiResp.data}`);
  }, [apiResp.data]);
}

i.e. only use the data of the useRequest as a dependency.

Sign up to request clarification or add additional context in comments.

Comments

1

First params for useRequest is a function who return a promise : () => axios(url)

Example with axios : Here

Example with custom useApi : Here

3 Comments

This is a good example, axios is more useful to work with requests, thank you
the two example use useRequest that allow to handle promise
my bad i dont know that useRequest can be use just like useRequest(url) ^^

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.