Cleaner React #1: How to derive state in functional components?
Hi, It’s been a long time since I wrote my first blog post (in Turkish) and it was my last until today. I’ve learned a lot of about creating a product and I’ll try to share all the knowledge I have gained in the last 3 years. I’m starting with my most handy tool, React. I won’t keep those posts long, I’ll just explain what I want to explain and that’s it.
What is ‘deriving’ ?
Deriving means producing something from another thing or things in general. In React, it means creating a new value based on existing values.
How to derive values in modern React?
Let’s say you have two different state definitions like those below;
const [firstName, setFirstName] = useState('Mert');
const [lastName, setLastName] = useState('Duzgun');
And you need to render the full name ‘Mert Duzgun’ in the same component. What would you do to achieve this?
Some people would define another state and store the full name inside it;
const [firstName, setFirstName] = useState('Mert');
const [lastName, setLastName] = useState('Duzgun');
// Bad approach
const [fullName, setFullName] = useState(`${firstName} ${lastName}`);
Which is totally unnecessary. A better approach would be using useMemo
const [firstName, setFirstName] = useState('Mert');
const [lastName, setLastName] = useState('Duzgun');
// Good approach
const fullName = useMemo(() => `${firstName} ${lastName}`, [firstName, lastName]);
But in my opinion, this is still not the best approach for this specific use case. Because this is a cheap calculation and re-calculating the fullName
value in every render won’t affect the performance in a noticeable way considering the hardware we use in 2022.
This means using useMemo
is okay but not the best solution when we don’t have an expensive calculation inside it. Instead, you can just declare a plain JavaScript variable and do the same calculation.
const [firstName, setFirstName] = useState('Mert');
const [lastName, setLastName] = useState('Duzgun');
// Best approach for this case
const fullName = `${firstName} ${lastName}`;
This mindset will make our codebase cleaner and performant enough. We can always use memoization tools if we encounter with a performance issue. But always start simple, don’t make early optimizations.
If you don’t know what memoization is, ChatGPT wrote a blog post about it.
Thank you for reading, may the code be with you.