skip to Main Content

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


  1. 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:

    1. 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.

    2. Performance: Using separate useState hooks for each state variable allows React to optimize re-renders. When you update a state using useState, 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:

    import React, { useState } from 'react';
    
    const MyComponent = () => {
      const [email, setEmail] = useState('[email protected]');
      const [name, setName] = useState('testName');
    
      // Use the individual state variables (email and name) in your component logic here
    
      return (
        <div>
          {/* Your JSX goes here */}
        </div>
      );
    };```
    
    Following this approach, you'll have cleaner, more efficient, and maintainable code that aligns with React's best practices for handling state in functional components.
    
    Login or Signup to reply.
  2. Try this example:

    export default function App() {
      useEffect(() => {
        console.log("component rerender!") 
      })
      const [myState, setMyState] = useState({
        name: "ahmed",
        isAdmin: "false"
      });
      return (
        <div>
          <button onClick={() => {
            setMyState(prev => {
              return {
                ...prev,
                isAdmin: true
              }
            })
          }}>Make it admin</button>
        </div>
      );
    }
    

    you will see each time you set isAdmin to true 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 example

    export default function App() {
      useEffect(() => {
        console.log("component rerender!");
      });
      const [name, setName] = useState();
      const [isAdmin, setIsAdmin] = useState();
      return (
        <div>
          <button
            onClick={() => {
              setIsAdmin(true);
            }}
          >
            Make it admin
          </button>
        </div>
      );
    }
    

    you won’t face that since isAdmin is boolean now and React can easily detect if its new value is different from the old one using Object.is.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search