What is the best way to handle state in React functional components? using a single object like:
const [state, setState] = useState ({
email:[email protected],
name:"tesName"
})
or should I use useState
for each state variable
const [email, setEmail] = useState("[email protected],")
const [name, setName] = useState("tesName")
tried both methods. just wanted to know which one is better and why?
2
Answers
In React functional components, the most recommended way to handle state is by using the useState hook for each state variable. While using a single object like const
state = { email: '[email protected]', name: 'testName' };
might seem convenient at first, it can lead to potential issues and is generally not considered a best practice. Here’s why:Immutability: React relies on immutability to efficiently determine when to re-render components. When you use the
useState
hook, React knows that a specific state variable has changed, and it can update only the relevant parts of the component tree. If you use a single object to hold multiple state variables, changing one property of the object would mutate the object, and React might not detect the change correctly, leading to unexpected behavior and bugs.Performance: Using separate
useState
hooks for each state variable allows React to optimize re-renders. When you update a state usinguseState
, React can keep track of the individual states’ changes. In contrast, when using a single object for multiple state variables, each state update would require the entire object to be recreated, leading to potential performance bottlenecks, especially in large and complex components.So, it’s generally recommended to use the
useState
hook for each state variable:Try this example:
you will see each time you set
isAdmin
totrue
the component rerenders, this makes sense since the state is an object so it does not matter if it is set to the exact same previous value, it will always be treated like it got a new completely different value. therefore the component rerenders.however, if you make each property of your object
useState
hook like in this exampleyou won’t face that since
isAdmin
isboolean
now and React can easily detect if its new value is different from the old one usingObject.is
.