DEV Community

loading...

Discussion on: React Clean Code - Simple ways to write better and cleaner code

Collapse
lequanghuylc profile image
Lê Quang Huy • Edited

Thanks for writing this article. In my opinion, clean code also means it's easier to upgrade it to be the more complex code, it'll be clean when you have your reasons ( and be sure other maintainers know your reasons via docs).

1 & 2 Conditional rendering

in order to avoid weird crash on some Android devices (assuming that we all try React Native someday), this is what I use all the time

<>
 {Boolean(showConditionalText) && <ConditionalTextComponent />}
</>
Enter fullscreen mode Exit fullscreen mode

This will prevent someone to assign a text variable to showConditionalText, it's fine on the web because we can render text as direct child.

4 String props

if you use curly braces, it'll be more convenient to convert it to variable later, and you will convert alot

// from
<Greeting personName={"John"} />
// to
<Greeting personName={userInfo.name} />
Enter fullscreen mode Exit fullscreen mode

It's more like Class Component vs Functional Component in the past, everyone wants to write a functional component in the beginning, but ends up converting it to class component.

8

Just want to share another way to deal with states, it does not relate much to your example. It's when you have dozen of useState variables, and the docs recommend useCallback, so the function always have most updated values. If keeping track of when to use useCallback or normal function, keeping track of the values cost you too much time, you can use a mutable variable and you can access anytime without useCallback

const [entityAData, setEntityAData] = useState(initialValueA);
const [entityBData, setEntityBData] = useState(initialValueB);

const entityADataRef = useRef(initialValueA);
const entityBDataRef = useRef(initialValueB);

useEffect(() => {
  entityADataRef.current = entityAData;
}, [entityAData]);
useEffect(() => {
  entityBDataRef.current = entityBData;
}, [entityBData]);

// entityADataRef.current and entityBDataRef.current will always be updated. free to use it as ready only variable, without callback

// we can write a custom hook to keep it short and avoid repeating code
Enter fullscreen mode Exit fullscreen mode