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

Image of AssemblyAI

Automatic Speech Recognition with AssemblyAI

Experience near-human accuracy, low-latency performance, and advanced Speech AI capabilities with AssemblyAI's Speech-to-Text API. Sign up today and get $50 in API credit. No credit card required.

Try the API

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.

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay