DEV Community

Lautaro Suarez
Lautaro Suarez

Posted on

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

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.