Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UI not re-rendering on state update using React Hooks and form submission

I'm trying to update a UI using React Hooks and a form. I have a state set to monitor the value on the form and when I click submit, I want to add this value to an array (held in state) and display it on the UI. My problem is that when I submit the value, although it is added to the array (and state is updated), the UI only updates when I change the value in the input.

My Component is as follows:

const PushToArrayUpdateState = () => {

    const [array, setArray] = useState([]);
    const [formVal, setFormVal] = useState(``);

    const handleSubmit = event => {
        event.preventDefault();
        let updateArray = array;
        updateArray.push(formVal);
        console.log(updateArray);
        setArray(updateArray);
    };

    return (
        <div>
            <form onSubmit={handleSubmit}>
                <input type="text" name="arrayVal" onChange={e => setFormVal(e.target.value)} />
                <input type="submit" value="Submit" />
            </form>
            <div>
                {array.map((val, index) => <p key={index}>{val}</p>)}
            </div>
        </div>
    );
};

You can also see this [not] working at: https://codesandbox.io/s/p3n327zn3q

Has anyone got any suggestions as to why the setArray in the handleSubmit function is not automatically causing the component to re-render?

like image 462
Ed Wright Avatar asked Apr 25 '19 19:04

Ed Wright


People also ask

Why is my React component not re rendering?

If React fails to do re-render components automatically, it's likely that an underlying issue in your project is preventing the components from updating correctly.

How do you force re-render React hooks?

Use the . forceUpdate() method to force a rerender and update the view. Once triggered, this method will update each child of the component. It's not recommended to use the component. forceUpdate() method unless you're sure you need it.

How do you update state in React hooks?

To update the state, call the state updater function with the new state setState(newState) . Alternatively, if you need to update the state based on the previous state, supply a callback function setState(prevState => newState) .

Why does the React useState hook not update immediately?

The answer: They're just queues setState , and React. useState create queues for React core to update the state object of a React component. So the process to update React state is asynchronous for performance reasons. That's why changes don't feel immediate.


1 Answers

Instead of

let updateArray = array;

Try this:

const updateArray = [...array];

https://codesandbox.io/embed/qxk4k3zmzq

Because arrays in JS are reference values, so when you try to copy it using the = it will only copy the reference to the original array.

like image 166
Roman Unt Avatar answered Oct 01 '22 09:10

Roman Unt