Source:  Twitter logo

I created a functional component MyComponent using hooks. I would like to know if it is fine to pass setState to another function renderList? I tried it works fine but according to hooks docs: Only call Hooks at the top level. Don’t call Hooks inside loops, conditions, or nested functions. Does this case count as calling hook from nested functions?

const MyComponent = (listProps) {
  const [state, setState] = useState(false);
  return (
    <div>
      renderList(listProps, setState);
    </div>
  );
}

renderList(listProps, setState){
  return (
    <ul>
     {
       listProps.map(item => {
         // call setState() with a value here;
         return <li>{item}</li>;
       });
     }
    </ul>
  );
}

The above manner of passing the setter to a function is perfectly fine and doesn't count as a scenario for

Only call Hooks at the top level. Don’t call Hooks inside loops, conditions, or nested functions

because you are actually calling the hook useState at the top of the functional component. The setter returned by useState and be called anywhere, either by passing it as a prop to child component or to a function returning JSX elements

The only thing that you need to take care of is that you are not calling the setter in render directly, but on an event or in an effect.

P.S. There are some syntactical errors that you need to rectify in your code though

Working demo

const MyComponent = ({listProps}) => {
  const [state, setState] = React.useState('');
  return (
    <div>
      {renderList(listProps, setState)}
    </div>
  );
}

const renderList = (listProps, setState) =>{
  return (
    <ul>
     {
       listProps.map(item => {
         // call setState() with a value here;
         return <li onClick={() => setState(item)}>{item}</li>;
       })
     }
    </ul>
  );
}

ReactDOM.render(<MyComponent listProps={['First', 'Second', 'Third']} />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<div id="root" />
4 users liked answer #0dislike answer #04
Shubham Khatri profile pic
Shubham Khatri

Copyright © 2022 QueryThreads

All content on Query Threads is licensed under the Creative Commons Attribution-ShareAlike 3.0 license (CC BY-SA 3.0).