Using React Hooks with Fetch API

Sara Bastian
3 min readJan 26, 2021

Fetching from a Rails API and Setting State with useEffect

For my final project with Flatiron School, I decided to level up my design game and use Material UI to style the frontend, which forced me to get comfortable with React hooks fast, since the framework is rooted in and best matched for functional components. At first, I struggled to find declarative on how to manage the state in a functional component specifically when fetching data from a Rails API, but as soon as I started using the useEffect hook, life managing state and passing down props as I knew it became simpler.

The useEffect hook communicates to React that the component needs to do something after it renders the page. It runs after the first render and after every update, performing both the mounting and updating tasks that the componentDidMount and componentDidUpdate functions perform for a class component. Even better, actions or effects rendered with useEffect do not block the browser from updated the screen.

To walk through an example, I implemented the useState hook to set the state and useEffect hook below to fetch all of my data from my supporterships model in my Rails backend. To import built-in Hooks in React, use the API below.

With useState (which accepts a new state value and queues up a re-render), I set the state of supporterships to be the data (an array of objects in this case) I was getting back from my fetch.

From there, I was able to take this information, and use it as I please. Here, I used a filter function to grab all the supporterships that matched the current user’s id, for the purpose of eventually passing that resulting array to a component that would display all the projects the current user is supporting (my app was essentially a platform for software developers to share projects they’re involved in, support other developer’s projects, and engage in dialogue with each other; think Kickstarter but for software engineers). Note — The second argument, [], is necessary for the useEffect to prevent an infinite loop.

In another iteration of this same logic, when creating a new supportership (i.e. supporting/following another user’s project), I first fetched all the supporterships from my backend database, set the state equal to the fetched data, and in the function that calls the ‘POST’ method fetch request, pushed the newly created supportership into supporterships array using a spread operator, like so:

If you do not import the hook API, you can also call React in front of that hook.

useEffect allows software writers to express various side effects the page can take after the component initially renders. In this simple way, managing state and passing props from component to component makes your app cohesive and easy to maintain.

--

--

Sara Bastian

full-stack developer exploring how software can solve real-world problems | https://sarabastian.com/