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

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

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.

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

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

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay