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 tool

Transforming Interviews into Publishable Stories with AssemblyAI

Insightview is a modern web application that streamlines the interview workflow for journalists. By leveraging AssemblyAI's LeMUR and Universal-2 technology, it transforms raw interview recordings into structured, actionable content, dramatically reducing the time from recording to publication.

Key Features:
🎥 Audio/video file upload with real-time preview
🗣️ Advanced transcription with speaker identification
⭐ Automatic highlight extraction of key moments
✍️ AI-powered article draft generation
📤 Export interview's subtitles in VTT format

Read full post

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.

Heroku

This site is powered by Heroku

Heroku was created by developers, for developers. Get started today and find out why Heroku has been the platform of choice for brands like DEV for over a decade.

Sign Up

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay