DEV Community

Discussion on: I replaced useState hook with custom one

Collapse
 
dance2die profile image
Sung M. Kim

I tend to implement such a hook with useReducer after reading @leewarrickjr's awesome article,

You will see that, with useReducer, you specify "how" to handle state changes.

So you can write a merge function as a reducer and pass the initial state as shown below.

const merge = (oldState, newState) => ({ ...oldState, ...newState });
const initialState = { name: "", email: "", phone: "" };

export default function App() {
  const [state, setState] = React.useReducer(merge, initialState);

  return (
    <div className="App">
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

The working code is below. (check the console output after submit).

Collapse
 
leewarrickjr profile image
Lee Warrick

Nice work!

Collapse
 
dance2die profile image
Sung M. Kim

Thanks, mate~! and for the post!