DEV Community

Discussion on: How to sync props to state properly in React Hooks

Collapse
 
dance2die profile image
Sung M. Kim • Edited

Thank you for the post, Paramanatham.

I am not sure if the code snippet is stripped-down version of actual code, you struggled with.

For this particular case, there'd be no need to save the prop to the state at all.

Forked Sandbox.

Edit props-to-state-react-hooks

// You can destructure only 👇 needed props  
const Profile = ({ name, email }) => {
  return (
    <div>
      <p>
        <strong>Name: </strong>
        {name}
      </p>
      <p>
        <strong>Email: </strong>
        {email}
      </p>
    </div>
  );
};

const App = () => {
  // irrelevant code removed for brevity
  const [state, setState] = useState({ ... });
  const handleChange = () => { ...  };

  return (
    <div className="App">
      {/* Pass only "needed" props 👇 /*}
      <Profile name={state.name} email={state.email} />
      <button onClick={handleChange}>Change Profile</button>
    </div>
  );
};

Now the Profile is dumb component, which depends on the props only, which also you can further optimize using useMemo or memo()

Collapse
 
learnwithparam profile image
Paramanantham Harrison

Thanks Kim, I understood, this example doesn't make much sense. It was created just to showcase how to sync props to state if there is a need for internal state change without the props change.

Example in a tabbed layout where you already have the data as props, but the current tab has internal data changes which are not used outside. In this case, there is no need to lift the state to parent but can be managed inside the tab and have props as the initial state.