Writing code convention JS / React?

Hi, again! In the quest to understand syntax better, a quick question. In the example underneath, from codecademy, the function calculating the prime number is underneath the counter function reusing the prime function. In my mind it would make more sense to place the prime function above the counter function since counter uses prime. So why is it underneath? Is this a JS / React convention?
import React, { useState, useEffect } from 'react';

export const Counter = () => {

const [counter, setCounter] = useState(0);

useEffect(() => {
if (isPrime(counter)) {
document.body.style.backgroundImage = 'linear-gradient(to right, coral, teal)';
} else {
document.body.style.backgroundImage = "";
}
}, [counter]);

return (
<div>
<h2>Count: {counter}</h2>
<button onClick={() => setCounter(counter + 1)}>Click Me!</button>
</div>
);
};


const isPrime = (num) => {
const squareRoot = Math.sqrt(num)
for (let i = 2; i <= squareRoot; i++) {
if (num % i === 0) {
return false;
}
}
return num > 1;
};
import React, { useState, useEffect } from 'react';

export const Counter = () => {

const [counter, setCounter] = useState(0);

useEffect(() => {
if (isPrime(counter)) {
document.body.style.backgroundImage = 'linear-gradient(to right, coral, teal)';
} else {
document.body.style.backgroundImage = "";
}
}, [counter]);

return (
<div>
<h2>Count: {counter}</h2>
<button onClick={() => setCounter(counter + 1)}>Click Me!</button>
</div>
);
};


const isPrime = (num) => {
const squareRoot = Math.sqrt(num)
for (let i = 2; i <= squareRoot; i++) {
if (num % i === 0) {
return false;
}
}
return num > 1;
};
3 Replies
Joao
Joao2y ago
It depends. Normally, I would agree with you. However, when I open a react component file what I expect to see first is the React component, not some random function. The isPrime function clearly is a rather generic function, not one that exclusively belongs to this one component. It's probably written below it to signify that it can be placed in a separate file for utility functions. If this function was meant to be used exclusively by this component only, then the definition should go inside the component.
Å Marlon G
Å Marlon GOP2y ago
Right! So this is just a consequence of the codecademy lesson structure. In a real life example this would have been done in two ways, if I understand you correct: 1. isPrime would be in its own file, e.g. isPrime.js 2. It would be moved inside of Counter, and then at the top, I guess?
Joao
Joao2y ago
If it's already on another file, there's no need to define it again, you would simply import it the same way you do with useState, useEffector any other file If it's not in another file, then it would be defined inside the component. Doesn't matter where but normally that should come after the state.
Want results from more Discord servers?
Add your server