DEV Community

Lautaro Suarez
Lautaro Suarez

Posted on

1

Calling Hooks properly

We should always use hooks at the top level of our react application, before any early returns in order to prevent hooks being called every re-render and only be called when necessary. That`s what allows react to correctly preserve the state of Hooks between multiple useState and useEffect calls.

Noncompliant example

`

function Test() {
const [testCount, setTestCount] = useState(0);
if (testCount !== 0) {
useEffect(function() { // Noncompliant, this Hook is called conditionally
localStorage.setItem('testData', testCount);
});
}

return

{ getName() }
};

function getName() {
const [name] = useState('John'); // Noncompliant, this Hook is called from simple JavaScript function
return name;
};

`

Compliant solution

`
function Test() {
const [testCount, setTestCount] = useState(0);
useEffect(function() {
if (testCount !== 0) {
localStorage.setItem('testData', testCount);
}
});

const [name] = useState('John');
return

{ name }
};
`

This way we are not putting any hooks inside if statements and we can prevent it from suffering any unwanted render.

Hope someone found it useFull

Lautaro

AWS Q Developer image

Your AI Code Assistant

Generate and update README files, create data-flow diagrams, and keep your project fully documented. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (2)

Collapse
 
naucode profile image
Al - Naucode

Great article, you got my follow, keep writing!

Collapse
 
lausuarez02 profile image
Lautaro Suarez

Thank you so much! I appreciate it.

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay