Junior React Developer? 4 ways to give your project a more professional and impressive look
Learn how to boost your developer experience and keep your code easier to maintain and simpler for others to work on with you.
Read on if you’d like to:
- dramatically boost your developer experience,
- keep your code easier to maintain and simpler for others to work on with you,
- wow hiring engineers with the projects on your GitHub,
because this post was written for you!
1. Use Volta
Do any of these situations ring a bell?
- You clone a fresh repo, run npm install or yarn, and your terminal fills up with cryptic errors – only for you to discover later in the readme that the app runs solely on Node versions 13.9.0 through 14.4.0.
- At some point during your onboarding, a colleague mentions in passing “oh, by the way, building it needs Node 12”.
- Whenever someone tells you they can’t get your project running, your first question is always “Which Node and npm versions do you have at the moment?”.
- You work on several projects in parallel, and each one needs different versions of certain tools.
Volta fixes every one of these issues, and it does so remarkably well. This is everything you need to begin.
- Install it with
curl https://get.volta.sh | bashor, on Windows, use the instructions on their website. - In the root directory of your project, run the
volta pincommand to pin particular tool versions in package.json. For instance, after running these commands:
volta pin node@12.20
volta pin yarn@1.19
your package.json will gain the following lines:
"volta": {
"node": "12.20.2",
"yarn": "1.19.2"
}
As a result, anyone who has Volta installed and runs a command relying on Node or Yarn will automatically get exactly the same versions. If those versions are missing, Volta installs them first and then executes the command.
What makes Volta special is how incredibly easy it is to use – once you adopt it, you’ll wonder how you ever coped without it.
2. Use Storybook
I can’t picture working efficiently on anything bigger than a Todo app without Storybook.
Seriously. Sure, like most of us, I did work on big projects without it in the past, but ever since I began bringing Storybooks into my workflows, my productivity has gone up a lot. I recall, for instance, that to build some small component I had to click through the app to a particular screen just to make it show up. And if my changes triggered an app reload, I had to hunt for the component all over again.
Some developers notice this too and end up building a kind of /playground subpage that displays all pure components to make development and visual testing easier. That is roughly what Storybook is – just far less capable!
With Storybook, you write *.stories.tsx files next to your components, and in them you render those components with various props so that their different states are shown side by side. And because the stories files import your components, every change you make is reflected in Storybook in real time.
Having Storybook in your project nudges you towards component-driven development – that is, constructing a UI by beginning with basic, pure components and combining them into bigger screens.
Just like pure functions, pure components have three crucial properties:
- Testing them is easier. Because pure components have no side effects, you can test them deterministically simply by feeding them different sets of props and checking that they render the expected output. There’s no need to mock or intercept network requests.
- Reusing them is easier. Because pure components don’t depend on any hidden state, you should be able to drop them into various views of your app, or even reuse them in other projects, and they should just work.
- Composing them is easier. Rather than building every screen, view, or layout by writing CSS for each element from scratch every single time, you can put your screen together simply by placing pure components in a container and tuning the layout with styling props specific to that composition. You don’t have to create loads of “one-off” components like
TrendingPostsBottomButtonthat can never be reused due to their highly specific internal styling.
This only scratches the surface of the whole component-driven development paradigm mentioned above. If you’d like to grow as a UI engineer and spare yourself much of the frustration caused by poorly designed design systems, I recommend having a look at these websites:
- https://www.componentdriven.org/
- the atomic web design methodology
- https://storybook.js.org/tutorials/intro-to-storybook/
3. Put business logic into custom hooks
Let’s say we’re building a screen that should list every post available on our blog for the user. Having done our homework from the previous section, we’ve already written our pure components – PostsStast and Post – and tested them in Storybook. All that’s missing is a component that fetches the posts’ data and passes it down to its children.
Here’s one thing we might come up with:
export const AllPosts = () => {
const [posts, setPosts] = useState<null | PostData[]>(null);
const [postsCount, setPostsCount] = useState(-1);
const [viewedPostsIds, setViewedPostsIds] = useState<number[]>([]);
const [isError, setIsError] = useState(false);
useEffect(() => {
fetch("http://localhost:1337/posts")
.then((res) => res.json())
.then((data) => setPosts(data))
.catch(() => setIsError(true));
}, []);
useEffect(() => {
fetch("http://localhost:1337/posts/count")
.then((res) => res.json())
.then((data) => setPostsCount(data))
.catch(() => setIsError(true));
}, []);
if (isError) {
return <div>Error...</div>;
}
if (postsCount === -1 || !posts) {
return <div>Loading...</div>;
}
const transformedPosts = posts.map((post) => ({
...post,
isViewed: viewedPostsIds.includes(post.id),
}));
return (
<div>
<h1>All Posts</h1>
<PostsStats postsCount={postsCount} />
{transformedPosts.map((post) => (
<Post
key={post.id}
post={post}
isViewed={post.isViewed}
onClick={() =>
setViewedPostsIds((posts) => {
if (posts.includes(post.id)) {
return posts;
}
return [...posts, post.id];
})
}
/>
))}
</div>
);
};
This component handles… quite a lot.
To begin with, it sets up 4 distinct pieces of state, some of which depend on one another.
Next, we fetch the data, and because two endpoints have to be called, we need two useEffects.
After that, we run a few checks to decide whether an error or a loading state should be displayed.
And once the data has loaded successfully, we still have to merge the external data with our local state that tracks clicked articles.
Only then can we render the screen with the proper data.
To be fair, this example isn’t that bad. The problem is that if you keep coding like this, you’ll end up with components that have 300+ lines of code before they even reach the return statement. Components like that are difficult to read and maintain, and they can easily hide race conditions between various state values and effects.
How can you avoid it? Take a look:
export const AllPosts = () => {
const { posts, postsCount, isLoading, isError, view } = usePosts();
if (isLoading) {
return <div>Loading...</div>;
}
if (isError) {
return <div>Error...</div>;
}
return (
<div>
<h1>All Posts</h1>
<PostsStats postsCount={postsCount} />
{posts.map((post) => (
<Post
key={post.id}
post={post}
isViewed={post.isViewed}
onClick={() => view(post.id)}
/>
))}
</div>
);
};
There are several benefits to this approach:
- Anyone can tell right away what the component is meant to do.
- As long as its API stays the same, we can refactor, improve and test our custom
usePostswithout touching this component or any other one that uses it. - The
isLoadingandisErrorflags make it easy to decide which UI to render. - A new business requirement asks us to show posts somewhere else in the app? Not a problem! All the logic lives neatly inside the
usePostshook. - Custom hooks also compose really well. Need to display only viewed posts? Just write
useViewedPosts, which callsusePostsinternally and returns the filtered results.
For an in-depth guide on writing custom hooks, see the official (beta) React docs.
4. Write simple code
This final tip is probably the most important one, and also the most difficult to master.
Suppose you have to fetch some data and present it to a user in a table. There’s no need to build a boilerplate-heavy, obscure, object-oriented abstraction for the fetching and then pile another abstraction layer on top so you can use it in your functional React component. You could simply use a react-query hook to fetch the data and map it into a table within your component. Everything stays in one component, without obscure abstractions or indirections.
Simple code comes from a mix of picking precise variable names, designing reasonable APIs for your functions, writing clean code, and selecting the right tools for the task.
Ways to get better at it:
- Write plenty of code. Implement the same thing again with different libraries, patterns, or architectures. That’s how you learn which approaches suit which problems best.
- Spend time reading code and considering whether a snippet, a function, or even an entire feature could have been built in a simpler way.
- Follow (at least to a degree) programming communities where people share their knowledge as well as libraries and techniques you may not have heard of. Examples include programming subreddits like r/react and r/typescript, or following people such as Matt Pocock, Josh W. Comeau, or me :)
Thank you for reading 😊. Was any of these tips especially useful to you? Or perhaps you’d like to add something? Don’t hesitate to leave a comment or send us an email.