Reputation: 2804
As I have seen in the doc, useState
and useReducer
does the same job.
Just useReducer
need something to be done manually and is better for complex state.
My Question is, which is faster? I mean which will done a job in a less time?
Currently I am using useState
:
const [messages, setMessages] = useState({});
const setMessage = (message, room) => {
setMessages(messages => {
if (messages[room] !== undefined)
return {...messages, [room]: [message, ...messages[room]] };
else return { ...messages, [room]: [message] };
});
}
Here as you can see I store messages of every room with setMessages.
This works very well, but I am confusing will it be faster if I use useReducer
instead of useState
?
my message object is as below:
const message = {
id: 'randomid',
text: 'a message text',
date: new Date(),
user: 'user1',
sent: false,
received: false,
delevered: false
}
const room = 'somerandomeroomid';
Upvotes: 1
Views: 1265
Reputation: 200
As Mohamed Ramrami said -
useState is using useReducer under the hood
so theoretically useReducer is faster whatsoever remember that
Premature optimization is the root of all evil
so focus on code quality and readability and you should solve perf issue using some measuring technique the moment you will start encountering them that might not even happen, React is pretty optimised.
Upvotes: 3
Reputation: 12691
useState
is using useReducer
under the hood (React source code) :
function updateState<S>(initialState: (() => S) | S,): [S, Dispatch<BasicStateAction<S>>] {
return updateReducer(basicStateReducer, (initialState: any));
}
I don't think there would be any performance difference at all.
Upvotes: 2