DEV Community

Cover image for Most essential React patterns - api call
arfa
arfa

Posted on

1

Most essential React patterns - api call

Calling APIs is one of the vital parts of each web app, so it's essential to know how to do it in the best way. for those APIs that you fetch some data from a server
probably, you need to save those data on a state, and this cause rerender as well, so clearly you should care about when calling them and fetch their result

for most scenarios calling them inside an useEffect is a good choice but make sure that pass an empty array as the second argument to let useEffect execute once exactly like component did mount

useEffect(() => {
  fetch('api/sms')
    .then(result => {
      const sms = result.data
      console.log('COMPONENT WILL Mount messages : ', sms)
      this.setState({sms: [...sms.content]})
    })
}, [])
Enter fullscreen mode Exit fullscreen mode

so if you are dealing with class components, compoentDidMount would be your choice

function componentDidMount() {
  fetch('api/sms')
    .then(result => {
      const sms = result.data
      console.log('COMPONENT WILL Mount messages : ', sms)
      this.setState({sms: [...sms.content]})
    })
}
Enter fullscreen mode Exit fullscreen mode

written based on this article

API Trace View

How I Cut 22.3 Seconds Off an API Call with Sentry 👀

Struggling with slow API calls? Dan Mindru walks through how he used Sentry's new Trace View feature to shave off 22.3 seconds from an API call.

Get a practical walkthrough of how to identify bottlenecks, split tasks into multiple parallel tasks, identify slow AI model calls, and more.

Read more →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs