Refactoring Emory React App
What problems do we have?
- Components are hard to read: which leads into lower development speed and harder maintenance.
- Mixed state (little-state-machine + useContext + local state): Which leads into unperformant behavior and making easy to confuse responsibilities
- Mixed responsibilities: For example, spinners are set in a function and unset in other, or same happens with checkoutReadyButton
- No tests in CI pipeline: Which leads into a lot of manual testing and untracked regressions
Problem: Components are hard to read
- Index.js and checkoutPayment.js are huge
- Too much nested properties: foo.bar.baz.more.what ? foo.bar.baz.more.what : baz.bar.foo.bar.what
- Too flat component structure dealing into too many 1st level files /folders
Solution
- Spread components in parts
- Move request/api logic to services
- Remove unnecessary useState
- Use computed props for all jsx variables
- Group them in domain/tech folders
Effort
- Spread index.js + move request logic => 2 / 3 days
- Spread checkoutPayment + move request logic => 2 / 3 days
- Improve useState in favor of computed props: I'd wait to have redux for this one. Would add 1 / 2 days to reduxify both components
Problem: Mixed state
- Almost unused Little state machine
- Abuse of UseContext
- Huge appcontext with all mixed props
- Repeated props: (useForm / useState / useContext)
Solution
- Remove little state machine
- Remove useContext
- Migrate to redux / xstate
- Refactor form components to use best practices around react tools
Effort
- Remove little state machine: 1/2 day
- Remove useContext: Cannot do it in one time. Need to remove feature by feature while we migrate it to redux
- Migrate to redux / xstate: Choose one and go for it. Will be less than 1/2 day to set up core config and will be reduxifying things in appcontext. I estimate around 2 / 3 days for all app to be reduxified.
- Refactor forms: N/A
Problem: Mixed Responsibilities
- Loaders: We set them to true and false imperatively from the view. And we only control loading for some requests
- Error handling: At the moment we are handling toasts in the view as well
- Enabled / disabled buttons set imperatively: This creates the need of too much business logic.
- All these handling mentioned above happen along different files for same feature
Solution
- Using redux: enforces handling each loading / error / success on each request, isolating its own loader / error business logic in one place
- Using selectors: Computed properties are the way of calculating values without saving them to new variables like we do everywhere with useState. This will save much setFoo() logic and cleaning logic as well.
Effort
- Using redux: Already estimated that in previous slide
- Using selectors: Will need to check all props read by components and refactor them so there is never errors trying to access a deep prop and make it readable in the jsx. This is apart of redux estimation and would be 2 / 3 days depending on what we find
Problem: No tests in CI pipeline
- Slow development delivery
- Error prone app
- Untracked regressions
- Extra work for finding/solving bugs
Solution

Solution

Effort
- For e2e / behavior testing : 3 days max
- For others: depending on the isolation level but around 2 weeks
- Also, once we have everything set up, we'd need to start adding test to our Definition Of Done, so we deliver each ticket with its appropriate contract and we can stop thinking about it.
Implementation Example
// useManageGift.js
import React, { useEffect, useState } from "react";
import { useParams } from "react-router-dom";
export default function useManageGift() {
const [refreshOrder, setRefreshOrder] = useState(true);
const [order, setOrder] = useState(null);
const [isLoading, setIsLoading] = useState(false);
let { token } = useParams();
// Fetch order on load or when refresh is explicitly requested.
useEffect(() => {
if (refreshOrder && !isLoading) {
fetchRecurringOrder();
}
}, [refreshOrder, isLoading]);
const fetchRecurringOrder = async () => {
const recurringOrderUuid = document
.getElementById("manage-gift-app")
.getAttribute("data-recurring-order-uuid");
setIsLoading(true);
setRefreshOrder(false);
const response = await fetch(
`/jsonapi/orders/recurring/${recurringOrderUuid}?include=order_items`,
{
method: "GET",
headers: {
"Content-Type": "application/vnd.api+json",
"Commerce-Cart-Token": token,
},
}
);
if (response.ok) {
setIsLoading(false);
setOrder(await response.json());
}
};
return {
isLoading,
setIsLoading,
refreshOrder,
setRefreshOrder,
order,
setOrder,
};
}
// useManageGift.js
import { useEffect } from "react";
import { useDispatch } from "react-redux";
import { fetcher } from "../helpers/global";
export default function useManageGift() {
const { isLoading, order, refreshOrder } = useSelector(selectGift);
const dispatch = useDispatch();
// Fetch order on load or when refresh is explicitly requested.
useEffect(() => {
if (refreshOrder && !isLoading) {
dispatch(FETCH_RECURRING_ORDER);
}
}, [refreshOrder, isLoading]);
return { order };
}
// checkout.reducer (or other reducer) I made this with a typical redux implementation but with xstate we can save some boilerplate
// ...some boilerplate
const initialState = { isLoading: false, order: null, refreshOrder: true, error: null }
const fooReducer = (state = initialState, action) => {
// Each async action has a success and an error
switch(action) {
case FETCH_RECURRING_ORDER:
return { ...initialState, isLoading: true }
case FETCH_RECURRING_ORDER_SUCCESS:
// we dont need to set loaders and errors in the view, if someone dispatches this in any place will need same props
// also, the responsibility remains here, no weird things to do and dealing with react renders. Loaders / errors will be
// 100% deterministic
return { ...state, isLoading: false, order: action.payload }
case FETCH_RECURRING_ORDER_ERROR:
return { ...state, isLoading: false, order: null, error: action.payload }
}
}
// checkout.selectors
// you can pick the state
export const selectGift = state => state.checkout
// Or you can use reselect for computing properties and memoizing them
// if we needed a deep prop in the response we could do something like
// https://github.com/reduxjs/reselect
export const selectWeirdDeepProp = createSelector(selectGift, gift => gift?.foo?.bar?.baz )
// checkout.services
function fetchRecurringOrder() {
// some code...
return fetcher(/* some code... */)
}
// checkout.sagas (or whatever we use for side effects)
function fetchRecurringOrderSaga() {
try {
// you can use selectors or functions here
const params = yield call(useParams)
const whateverPropInState = yield select(propInState)
// you call to your service (this is also cool done with redux-observable and Epics,
// as they include services as dependency and you dont have to import them because they are always in scope)
const result = yield call(fetchRecurringOrder, params, whateverPropInState)
// you always end a saga dispatching another action (success / error)
yield put(FETCH_RECURRING_ORDER_SUCCESS, result)
} catch(e) {
yield put(FETCH_RECURRING_ORDER_ERROR, e)
// Maybe handle a toast here...
}
}
export function watchFetchRecurringOrderSaga() {
// this is listening for the latest action (to prevent triggering it multiple times) but there are many strategies
// to listen to actions. You can also debounce actions and other powerful stuff for cases like async validation.
yield takeLatest(FETCH_RECURRING_ORDER, fetchRecurringOrderSaga)
}Other lectures
https://dev.to/michielmulders/why-use-redux-reasons-with-clear-examples-1108
Emory refactor
By Diego Segura
Emory refactor
- 38