r/reactjs • • Apr 30 '20

Needs Help Beginner's Thread / Easy Questions (May 2020)

[deleted] — view deleted post

39 Upvotes

401 comments sorted by

View all comments

2

u/ytdl-node May 09 '20

If I am using React hooks, let's say for a state change, I'd normally write something like:

// In function App()
const [username, setUsername] = useState('');
const [age, setAge] = useState(0);

console.log(username, age);

Now if I pass the setUsername and setAge functions to a component let's say 'A' in the following fashion:

<A setUsername={setUsername} setAge={setAge} />

And in my component 'A', I update the username and the age.

function A(props) {
    const { setUsername, setAge } = props;
    setUsername('user');
    setAge('5');
}

This will cause the main App to re-render twice right? Is it not better if I just use an object for the state? E.G.:

const [state, setState] = useState({
    username: '',
    age: 0,
});

Why do we not use this instead?

1

u/dance2die May 09 '20

You can use useReducer should you need to update multiple states at once. Pass down a dispatch or an "action" calling dipsatch down to a child component would work.

1

u/cmdq May 10 '20 edited May 10 '20

it doesn't re-render twice

react applies state changes asynchronously and batches calls, so multiple chained calls do not result in excessive re-rendering

i'd encourage you to always challenge your initial assumptions, especially when it comes to perceived performance issues :)