iTranslated by AI
A Guide to Role-Driven Development [Frontend Edition]
Implementing Components with a Focus on Roles
Suppose you are implementing a component that fetches hoge and fuga from a server and displays them on the screen.
Which of the following component coding styles do you think is better?
Pattern 1
const HogeFugaComponent = () => {
const [isLoadingHoge, setIsLoadingHoge] = useState(false);
const [hoge, setHoge] = useState(null);
const [isLoadingFuga, setIsLoadingFuga] = useState(false);
const [fuga, setFuga] = useState(null);
useEffect(() => {
fetchHoge()
.then(hoge => {
setHoge(hoge);
})
})
useEffect(() => {
fetchFuga()
.then(resFuga => {
setFuga(resFuga);
})
})
return <div>{fuga}{hoge}</div>
}
Pattern 2
const HogeFugaComponent = () => {
// Functionality to display hoge
const [isLoadingHoge, setIsLoadingHoge] = useState(false);
const [hoge, setHoge] = useState(null);
useEffect(() => {
fetchHoge()
.then(hoge => {
setHoge(hoge);
})
})
// Functionality to display fuga
const [isLoadingFuga, setIsLoadingFuga] = useState(false);
const [fuga, setFuga] = useState(null);
useEffect(() => {
fetchFuga()
.then(resFuga => {
setFuga(resFuga);
})
})
// Rendering
return <div>{fuga}{hoge}</div>
}
For those unfamiliar with React, useState is a state management function in React. It returns an array where the first element is the actual state and the second is the setter. useEffect is the place in a React component where you write code that causes side effects, such as communication with a server. useEffect is executed when the component is mounted.
I recommend Pattern 2. This is because gathering related items together, as in Pattern 2, makes modularization easier. Modularization in React can be achieved through componentization or custom hooks.
const HogeFugaComponent = () => {
// Functionality to display hoge
const [hoge, isLoadingHoge] = useHoge(); // Custom hook. Implementation omitted.
// Functionality to display fuga
const [fuga, isLoadingFuga] = useFuga(); // Custom hook. Implementation omitted.
// Rendering
return <div>{fuga}{hoge}</div>
}]
To Write Like Pattern 2
Both Pattern 1 and Pattern 2 group similar functionalities. Pattern 1 organizes them by the types of features provided by React components. Pattern 2 organizes them by the functional units the component aims to provide.
How can we write like Pattern 2? This can be achieved by explicitly stating the component's roles. You can list the roles in the documentation and use comment separators within the code to indicate them as follows:
/**
* Roles:
* - Functionality to display hoge
* - Functionality to display fuga
*/
const HogeFugaComponent = () => {
/* ------------------------ */
/* Functionality to display hoge */
/* ------------------------ */
const [hoge, isLoadingHoge] = useHoge();
/* ------------------------ */
/* Functionality to display fuga */
/* ------------------------ */
const [fuga, isLoadingFuga] = useFuga();
// Rendering
return <div>{fuga}{hoge}</div>
}
No one would go out of their way to write it like this. This is the advantage of explicitly stating the roles in the code as comments.
/**
* Roles:
* - State management functionality
* - Side effect functionality
*/
const HogeFugaComponent = () => {
/* ------------------------ */
/* State management functionality */
/* ------------------------ */
const [isLoadingHoge, setIsLoadingHoge] = useState(false);
const [hoge, setHoge] = useState(null);
const [isLoadingFuga, setIsLoadingFuga] = useState(false);
const [fuga, setFuga] = useState(null);
/* ------------------------ */
/* Side effect functionality */
/* ------------------------ */
useEffect(() => {
fetchHoge()
.then(hoge => {
setHoge(hoge);
})
})
useEffect(() => {
fetchFuga()
.then(resFuga => {
setFuga(resFuga);
})
})
// Rendering
return <div>{fuga}{hoge}</div>
}
Actual Example
/**
* Roles:
* - Search for channels.
* - Display a list of channels. -> Delegate to ChannelList
* - Selecting a channel navigates to the chat screen. -> Delegate to ChannelList
*/
export const ChannelIndex: React.FC = () => {
/* ------------------------ */
/* Common */
/* ------------------------ */
const history = useHistory();
const location = useLocation();
const params = queryString.parse(
location.search,
) as Partial<ChannelIndexPageQuery>;
/* ------------------------ */
/* Displaying the channel list */
/* ------------------------ */
const [isLoading, setIsLoading] = useState(false);
const [channels, setChannels] = useState<Channel[]>([]);
const [total, setTotal] = useState(0);
// When the URL changes (i.e., search conditions change), scroll to the top of the page
useEffect(() => {
window.scrollTo(0, 0);
}, [location]);
/* ------------------------ */
/* Channel search */
/* ------------------------ */
// NOTE: Searching basically follows this flow:
// 1. Push to URL
// 2. Detect URL changes, get params from the URL, and fetch
// The reason for this approach is that by keeping search conditions in the URL rather than in internal state, sharing via links becomes possible.
const PAGE_UNIT = 20;
const currentPage = Number.parseInt(params.currentPage || '1', 10);
const handleSearchPage = (page: number) => {
history.push({
search: queryString.stringify({
...params,
currentPage: page.toString(),
}),
});
};
const handleSearchSubmit = (text: string) => {
history.push({
search: queryString.stringify({
...params,
keyword: text,
}),
});
};
useEffect(() => {
const offset = (currentPage - 1) * PAGE_UNIT;
const limit = PAGE_UNIT;
setIsLoading(true);
ChannelRequest.search({
keyword: params.keyword,
offset: offset.toString(),
limit: limit.toString(),
})
.then((res) => {
if (!res.isSuccess) {
notify('error', res.error);
return;
}
setTotal(res.header.total);
setChannels(res.body);
})
.finally(() => {
setIsLoading(false);
});
}, [
// NOTE: Specifying 'params' directly causes a loop, so dependency properties are explicitly specified.
currentPage,
params.keyword,
params.limit,
params.offset,
]);
return (
<div className={classes.Cover}>
<Container className={classes.Container}>
<Search className="mb-3 h-2" onSubmit={handleSearchSubmit} />
<ChannelList
channels={channels}
isLoading={isLoading}
currentPage={currentPage}
pageUnit={PAGE_UNIT}
total={total}
handlePage={handleSearchPage}
searchKeyword={params.keyword || ''}
/>
</Container>
</div>
);
};
I think we can also check the corresponding roles in tests.
describe('<ChannelIndex />', () => {
describe('Ability to search for channels.', () => {
test.todo('Search for channels by keyword');
test.todo('Search for channels on the next page');
test.todo('Search for channels on the previous page');
});
});
Conclusion
I came up with this writing style while thinking about the following:
In the end, it seems to have the same effect as "Programming by Intention" from TDD.
Discussion