Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

functional component set useState in conditional function

If you set useState variable in function where is condition like "if statement" it's ok? I read that you shouldn't use hook's in conditions but is it also true for setting the state? Example will show what i mean. If I cant do like this how can I set it right way if I have multiple variables and if conditions. Please help me thanks

I'm aware of this: https://reactjs.org/docs/hooks-rules.html#explanation but I have some doubts

import React, { useState} from "react";

const MoreInfo = () => {

const [more_info, setMore_info] = useState("test");

const handleExpand = (event) => {
        if (icon_expand === 'expand_more') {
        setMore_info("test2");  // is this ok in if?
      }
}

  return (
 <IconButton onClick={handleExpand}>
);
};

export default MoreInfo;
like image 494
fr3sh Avatar asked Sep 05 '19 13:09

fr3sh


People also ask

Can we use useState in if condition?

We can use conditionals in the function in order to determine the correct value for the state variable. Passing a function to the useState method is useful when the initial state is the result of an expensive computation. The function we passed to useState will only be invoked on the initial render.

Can I use useState inside a function?

The useState hook is used to update the state in a React component. It is a hook that takes the initial state as an argument and returns an array of two entries. It can be used in a React class based component as well as a functional component (declared using the function or const keyword).

Can you initialize useState from a function?

With the useState hook, you can pass a function as an argument to initialize the state lazily. As discussed, the initial value is needed only once at the first render.

Can useState hook be used in functional components?

useState is a Hook that allows you to have state variables in functional components. You pass the initial state to this function and it returns a variable with the current state value (not necessarily the initial state) and another function to update this value.


1 Answers

The hook is useState. And the rules apply for that call only (and any other hook's call that might be using, and custom hooks, like useSomething).

The setState call is not a hook call. You're calling a method that was returned from a hook call. Infact React guarantees that the setState reference doesn't change between renders.

Rules of hooks:

Only Call Hooks at the Top Level

Only Call Hooks from React Functions

The following article might help you understand why these rules exist. It gives a visual explanation of hooks under the hood.

https://medium.com/@ryardley/react-hooks-not-magic-just-arrays-cd4f1857236e

function App() {
  
  // THE useState CALL SHOULD BE ON TOP LEVEL
  // CAN'T BE CALLED INSIDE ANY CONDITIONALS
  const [myState,setMyState] = React.useState(0); 
  
  // THE setState CALLS CAN BE ANYWHERE
  function changeCounter(value) {
    if (value === 'increment') {
      setMyState((prevState) => prevState + 1);
    }
    else if (value === 'decrement') {
      setMyState((prevState) => prevState - 1);
    }
  }
  
  return(
    <React.Fragment>
      <div>Counter: {myState}</div>
      <button onClick={() => changeCounter('increment')}>
        +
      </button>
      <button onClick={() => changeCounter('decrement')}>
        -
      </button>
    </React.Fragment>
  );
}

ReactDOM.render(<App/>, 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"/>
like image 135
cbdeveloper Avatar answered Sep 28 '22 19:09

cbdeveloper