React — Hooks — Global Context —useEffect(), useReducer() and Side Effects (API calls etc) Example

Adriaan Botha
The Apps Team
Published in
3 min readMay 23, 2019

Let’s try and simplify state management using the new API’s from React. This article is a test into the new React State and Context API’s.

Photo by Grant Porter on Unsplash

In Short —Looking through some articles which covers subjects like React Hooks and global Context and useState, I couldn’t comprehend and at first undertsand what exactly and how we would go about handling State with the new React global Context API, in short I have created a repo which retrieves news items using side effects eg. useEffect() from React, please see my repo here — https://github.com/adriaanbotha/React-Context-Hooks-Async also see the branch which uses the dummy users API here — https://github.com/adriaanbotha/React-Context-Hooks-Async/tree/create_users_list

Description

Basically motivated by StackBlit’s article and youtube video here — https://youtu.be/6uBgda52yEo, about React Hooks + Context API = Global State Pattern. I decided I like their approach and wanted to pursue and see if it can be used with side effect eg, API calls using fetch or axios or any of those to make it asynchronous. By using the useEffect() and useReducer() hooks from React this can be achieved.

My Two Cents

In my GitHub repo here — https://github.com/adriaanbotha/React-Context-Hooks-Axios, I use their idea and add my one cent's worth, really I didn’t add much but was excited again to be motivated that there are other’s that share the idea of making thing less complex in the over-architected and documented industry called programming. However, I wasn’t too happy with that yet, so I set out to create a repo which uses the Global Context this time with useEffect() and not using Redux but adding a Reducer with useReducer(). See the finished product here — https://github.com/adriaanbotha/React-Context-Hooks-Async.

In my approach, I simply added an API call, using axios to read a feed from the ABC news and display the results in an async way.

See the part below for retrieving the feed information inside the App.js file.

useEffect(() => {
dispatch({ type: 'FETCHING_ARTICLES' });

fetchAllArticles()
.then((data) => {
dispatch({ type: 'ADD_ARTICLES', data });
dispatch({ type: 'FETCHED_ARTICLES' });
})
.catch((error) => {
console.log('error ->', error);
});
}, []);

It uses the latest useEffect() function from React.

See the results from the console log above inside your browser's console.

Results

Broken Down

  • Create a Store with the createContext() inside store.js
  • Add your reducers inside app.js see the top part. In this example, I use useCombinedReducers() but you don’t need to do that.
  • Use selectors as a pattern for retrieving your Async call from the News API, this could also be any other pattern.

--

--

Adriaan Botha
The Apps Team

Claim to fame nothing, depending on Christ — EVERYTHING !!!