React Hooks must be called in the exact same order in every component render. This behavior is even mentioned on Eslint's react-hooks/rules-of-hooks
, but is it ok to return null before some hooks render in this following situation?
The Page component receives a prop called keyword
, and it's supposed to search for posts based on this keyword. But if the keyword is not defined, we'll not render the page since there's nothing to render to the user.
In this context, is it ok to conditional render before any hooks?
function Search({ keyword }) {
if(typeof keyword == "undefined") return null;
const [searchKeyword, setSearchKeyword] = useState(keyword);
const [searchPosts, setSearchPosts] = useState(await searchPosts(searchKeyword));
}
CodePudding user response:
No, that is not ok. You must call the exact same hooks in the exact same order each time your component renders. Calling 0 hooks on the first time and 2 on the second time will be a problem.
What you could do is split this into two components: An outer componet with no hooks that checks keyword
, and an inner component with all the hooks:
function Outer({ keyword }) {
if (typeof keyword === 'undefined') return null;
return <Inner keyword={keyword} />
}
function Inner({ keyword }) {
// Do stuff with the keyword, which must exist.
}