简体   繁体   中英

Calling a state update function within a state update function - useState hook in React Functional component

I have a callback function that updates two states.

  1. Simple increment and set of a state variable
  2. Updating another state from within the state update function of the first state utilizing the updated state value of the first state.

An example code is given below,

const [index, setIndex] = useState(-1);
const [fields, setFields] = useState([]); 

const callbackFunction = () => {
    setIndex(prevState => {
        const newIndex = prevState + 1;
        setFields(prevState => [...prevState, {id: newIndex, question: "", type: ""}]);
        return newIndex;
    });
};

//I will be calling the callbackFunction somewhere over here in my JSX

Please note that my initial description may not accurately describe the code. Apologies if so.

I want to know if the code I implemented is

  1. An anti patter or not
  2. Would cause any problems which I am not seeing at the moment

The red flag for me is the state update within a state update.

Thanks in advance for any information that would enlighten me.

  1. It is an anti pattern as it is not a custom hook and is a useState .
  2. It would be hard to debug in the future.

What you can do is:


const callbackFunction = () => {
    const newIndex = index+ 1;
    setIndex(newIndex);
    setFields([...fields, {id: newIndex, question: "", type: ""}]);
};

This IMO way cleaner and pretty straight forward, no nested code, no additional callback function inside setState and should work the same.

Simply do this

const [index, setIndex] = useState(-1);
const [fields, setFields] = useState([]); 

const callbackFunction = () => {
const newIndex = index+ 1;
    setIndex(prevState => newIndex);
 setFields(prevState => [...prevState, {id: newIndex, question: "", type: ""}])
};

Your intention is clear why you try to update the setFeilds inside the setIndex . You want to get the updated index and pass it to the setFeilds . Sure what your trying to do here is an anti-pattern. You could simply follow the above way to achieve what you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM