DEV Community

Discussion on: Write Custom Hooks in React

Collapse
 
mwoodson profile image
marques woodson

Here's an example of using the React.useReducer hook in the UserComponent defined in the article:

function UserComponent() {
  // userReducer is defined above in the article.
  const [state, dispatch] = React.useReducer(userReducer, initialState);

  const [input, setInput] = React.useState('');

  const updateInput = (input: string) => {
    setInput(input);
  };

  const updateName = () => {
    dispatch({
      type: 'SET_NAME',
      payload: input,
    });
  };

  return (
    <div>
      <h1>My name is: {state.name}</h1>
      <input value={input} onChange={e => updateInput(e.target.value)} placeholder="Enter name here" />
      <button onClick={updateName}>Submit</button>
      ...
    </div>
  );
}

I am using the useReducer hook to create state and dispatch variables. In the userReducer switch statement i have a SET_NAME case, which should just update the name property. We do that by dispatching an action of type SET_NAME, and with a payload of the new name. This happens in the above updateName method.

Does this make more sense?