<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: Adebayo Pokanu</title>
    <description>The latest articles on Forem by Adebayo Pokanu (@adezb).</description>
    <link>https://forem.com/adezb</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F908724%2F71d9dc9b-4106-4327-812d-e5259a73948e.jpeg</url>
      <title>Forem: Adebayo Pokanu</title>
      <link>https://forem.com/adezb</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/adezb"/>
    <language>en</language>
    <item>
      <title>How To Implement &amp; Set Input Value with React Hooks in a Counter Application.</title>
      <dc:creator>Adebayo Pokanu</dc:creator>
      <pubDate>Mon, 09 Jan 2023 13:25:45 +0000</pubDate>
      <link>https://forem.com/adezb/how-to-implement-set-input-value-with-react-hooks-in-a-counter-application-3c08</link>
      <guid>https://forem.com/adezb/how-to-implement-set-input-value-with-react-hooks-in-a-counter-application-3c08</guid>
      <description>&lt;p&gt;Hi techies!&lt;br&gt;
In this post, I will be putting you through on how to implement &lt;em&gt;set value&lt;/em&gt; function with &lt;em&gt;input tag&lt;/em&gt; and &lt;em&gt;button&lt;/em&gt; using the following React Hooks: &lt;strong&gt;useState&lt;/strong&gt;, &lt;strong&gt;useRef&lt;/strong&gt; and &lt;strong&gt;useReducer.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;We will be working on two counters; one will be controlled by &lt;strong&gt;useState&lt;/strong&gt; hook while the other will be controlled by &lt;strong&gt;useReducer&lt;/strong&gt; hook.&lt;br&gt;
The counters will be having the following functions: &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Increment&lt;/li&gt;
&lt;li&gt;Decrement&lt;/li&gt;
&lt;li&gt;Reset&lt;/li&gt;
&lt;li&gt;Set Value/handleClick&lt;/li&gt;
&lt;li&gt;handleOnChange&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Counter 1: useState Hook&lt;/strong&gt;&lt;br&gt;
The first thing to do here is to import the &lt;strong&gt;useState&lt;/strong&gt; hook from react.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import {useState} from "react";
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;After importing the &lt;strong&gt;useState&lt;/strong&gt; hook, the next thing to do is to set it up.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;useState&lt;/strong&gt; accepts two argument. The first one is a &lt;strong&gt;&lt;em&gt;value to store the data&lt;/em&gt;&lt;/strong&gt; of the state while the second argument is a &lt;strong&gt;&lt;em&gt;function to update the data&lt;/em&gt;&lt;/strong&gt; in the state value. We also set the default value to zero.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const [count, setCount] = useState(defaultValue || 0);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;&lt;em&gt;Functions and buttons&lt;/em&gt;&lt;/strong&gt;&lt;br&gt;
Now, we need to set the functions and buttons.&lt;br&gt;
Before setting anything, we need to import one more hook – &lt;strong&gt;useRef&lt;/strong&gt; hook. This hook is needed for our &lt;strong&gt;&lt;em&gt;Set Value function&lt;/em&gt;&lt;/strong&gt; and &lt;strong&gt;&lt;em&gt;input tag&lt;/em&gt;&lt;/strong&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { useState, useRef } from "react";
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;After importing, we set it up by declaring an &lt;em&gt;inputRef&lt;/em&gt; value and initialize it to null.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const inputRef = useRef(null);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;&lt;em&gt;Declaring the functions&lt;/em&gt;&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const increment = () =&amp;gt; setCount((countValue) =&amp;gt; countValue + 1);
const decrement = () =&amp;gt; setCount((countValue) =&amp;gt; countValue - 1);
const setValue = () =&amp;gt; setCount(inputRef.current.value - `${count}`);
const reset = () =&amp;gt; setCount(defaultValue);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;N.B:&lt;/em&gt; In the set value function, we use &lt;em&gt;&lt;strong&gt;template literal&lt;/strong&gt;&lt;/em&gt; to deduct count from &lt;code&gt;inputRef.current.value&lt;/code&gt; so that when the &lt;em&gt;inputed&lt;/em&gt; value is set to the &lt;code&gt;count&lt;/code&gt; variable, and the increment or decrement button is triggered, it will update the &lt;code&gt;count&lt;/code&gt; state starting from the inputed value instead of displaying the two values together.&lt;/p&gt;

&lt;p&gt;Final code set up.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { useState, useRef } from "react";

export default function App(defaultValue) {
 const [count, setCount] = useState(defaultValue || 0);
 const inputRef = useRef(null);

 const increment = () =&amp;gt; setCount((countValue) =&amp;gt; countValue + 1);
 const decrement = () =&amp;gt; setCount((countValue) =&amp;gt; countValue - 1);
 const setValue = () =&amp;gt; setCount(inputRef.current.value - `${count}`);
 const reset = () =&amp;gt; setCount(defaultValue);

return (
      &amp;lt;&amp;gt;
        &amp;lt;div className="counter__wrapper"&amp;gt;
         &amp;lt;div className="counter-box"&amp;gt;{count}&amp;lt;/div&amp;gt;

          &amp;lt;div className="counter-btn-wrapper"&amp;gt;
           &amp;lt;button
            disabled={count &amp;gt;= 20}
            className="counter__btn operation-btn"
            onClick={increment}
          &amp;gt; + &amp;lt;/button&amp;gt;

          &amp;lt;button className="reset-btn" onClick={reset}&amp;gt;
            Reset
          &amp;lt;/button&amp;gt;

          &amp;lt;button
            disabled={count &amp;lt;= 0}
            className="counter__btn operation-btn"
            onClick={decrement}
          &amp;gt; - &amp;lt;/button&amp;gt;
        &amp;lt;/div&amp;gt;
        &amp;lt;div className="set__value"&amp;gt;
          &amp;lt;div className="input__value"&amp;gt;
            &amp;lt;input ref={inputRef} name="number" type="text" placeholder="0" /&amp;gt;
          &amp;lt;/div&amp;gt;
          &amp;lt;button onClick={setValue}&amp;gt;Set Value&amp;lt;/button&amp;gt;
        &amp;lt;/div&amp;gt;
      &amp;lt;/div&amp;gt;
   &amp;lt;/&amp;gt;

)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Counter 2: useReducer Hook&lt;/strong&gt;&lt;br&gt;
As usual, we import &lt;strong&gt;useReducer&lt;/strong&gt; from react.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { useReducer } from "react";
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;&lt;em&gt;Declare a default/initial state variable.&lt;/em&gt;&lt;/strong&gt;&lt;br&gt;
Initialize it with a &lt;code&gt;counter&lt;/code&gt; object set to zero and &lt;code&gt;input&lt;/code&gt; object set to empty string.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const defaultState = { counter: 0, input: "" };
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;OR&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const initialState = { counter: 0, input: "" };
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;Note: You can declare your own preferred variable name.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Declare a &lt;code&gt;reducer&lt;/code&gt; function with a &lt;code&gt;switch&lt;/code&gt; statement. &lt;br&gt;
In the statement, we will be having five (5) cases and a default. The five (5) cases are:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;“increment”:&lt;/code&gt; to update the state of the counter by adding + 1&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;“decrement”:&lt;/code&gt; to update the state of the counter by subtracting -1&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;“reset”:&lt;/code&gt; to return the state of the counter to default value 0&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;“setvalue”:&lt;/code&gt; to update the state of the input value to whatever the user inputs&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;“updatecounter”:&lt;/code&gt; to update the state of the counter to the current value in the input
&lt;/li&gt;
&lt;/ul&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const defaultState = { counter: 0, input: "" };
const reducer = (state = { name: "" }, action) =&amp;gt; {
  switch (action.type) {
    case "increment":
      return { ...state, counter: state.counter + 1 };
    case "decrement":
      return { ...state, counter: state.counter - 1 };
    case "reset":
      return defaultState;
    case "setvalue":
      return { ...state, input: action.payload };
    case "updatecounter":
      return { ...state, counter: action.payload };
    default:
      throw new Error("Invalid action type");
  }
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;&lt;strong&gt;&lt;em&gt;Functions&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;increment&lt;/code&gt; with dispatch type set to “increment”&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;decrement&lt;/code&gt; with dispatch type set to “decrement”&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;reset&lt;/code&gt; with dispatch type set to “reset”&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;handleOnChange&lt;/code&gt; with event &lt;code&gt;(e)&lt;/code&gt; in the call back function and - &lt;code&gt;dispatch&lt;/code&gt; type set to &lt;code&gt;“setvalue”&lt;/code&gt;. It will also have a &lt;code&gt;payload&lt;/code&gt; set to &lt;code&gt;e.target.value&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;handleClick&lt;/code&gt; with dispatch type set to &lt;code&gt;“updatecounter”&lt;/code&gt;. The &lt;code&gt;payload&lt;/code&gt; will be set to &lt;code&gt;state.input&lt;/code&gt; and deducting the &lt;code&gt;counter&lt;/code&gt; with a &lt;strong&gt;_template literal _&lt;/strong&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;dispatch({
      type: "updatecounter",
      payload: state.input - `${state.counter}`,
    });
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;so that when the inputed value is set to the &lt;code&gt;counter&lt;/code&gt;, and the &lt;code&gt;increment&lt;/code&gt; or &lt;code&gt;decrement&lt;/code&gt; is triggered, it will update the &lt;code&gt;counter&lt;/code&gt; state starting from the inputed value instead of displaying the two values together.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Final code set up.&lt;/em&gt;&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { useReducer } from "react";

const defaultState = { counter: 0, input: "" };

const reducer = (state = { name: "" }, action) =&amp;gt; {
  switch (action.type) {
    case "increment":
      return { ...state, counter: state.counter + 1 };
    case "decrement":
      return { ...state, counter: state.counter - 1 };
    case "reset":
      return defaultState;
    case "setvalue":
      return { ...state, input: action.payload };
    case "updatecounter":
      return { ...state, counter: action.payload };
    default:
      throw new Error("Invalid action type");
  }
};

export default function App() {
  const [state, dispatch] = useReducer(reducer, defaultState);

  const handleClick = () =&amp;gt; {
    dispatch({
      type: "updatecounter",
      payload: state.input - `${state.counter}`,
    });
  };

  const increment = () =&amp;gt; {
    dispatch({ type: "increment" });
  };

  const decrement = () =&amp;gt; {
    dispatch({ type: "decrement" });
  };

  const reset = () =&amp;gt; {
    dispatch({ type: "reset" });
  };

  const handleOnChange = (e) =&amp;gt; {
    dispatch({ type: "setvalue", payload: e.target.value });
  };
return (
      &amp;lt;&amp;gt;
        &amp;lt;div className="counter-box"&amp;gt;
            {state.counter}
          &amp;lt;/div&amp;gt;

        &amp;lt;div className="counter-btn-wrapper"&amp;gt;
          &amp;lt;button
            disabled={state.counter &amp;gt;= 20}
            className="counter__btn operation-btn"
            onClick={increment}
          &amp;gt; + &amp;lt;/button&amp;gt;

          &amp;lt;button className="reset-btn" onClick={reset}&amp;gt;
            Reset
          &amp;lt;/button&amp;gt;

          &amp;lt;button
            disabled={state.counter &amp;lt;= 0}
            className="counter__btn operation-btn"
            onClick={decrement}
          &amp;gt; - &amp;lt;/button&amp;gt;
        &amp;lt;/div&amp;gt;

        &amp;lt;div className="set__value"&amp;gt;
          &amp;lt;div className="input__value"&amp;gt;
            &amp;lt;input
              onChange={handleOnChange}
              value={state.input}
              name="number"
              type="text"
              placeholder="0"
            /&amp;gt;
          &amp;lt;/div&amp;gt;
          &amp;lt;button onClick={handleClick}&amp;gt;Set Value&amp;lt;/button&amp;gt;
        &amp;lt;/div&amp;gt;
      &amp;lt;/&amp;gt;
)
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;That will be all for now.&lt;br&gt;
Check out for the full code and style implementation in my github &lt;a href="https://github.com/Adezb/Counter-App-Exam-Project"&gt;repo&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;You can as well follow me on &lt;a href="https://twitter.com/adezb_CEO"&gt;twitter&lt;/a&gt;&lt;/p&gt;

</description>
      <category>react</category>
      <category>counter</category>
      <category>usestate</category>
      <category>usereducer</category>
    </item>
  </channel>
</rss>
