React Hooks are added in React 16.8. we can use state and other React features without writing a class.

On this above example we will create a small task. When Click on Click to increase count button then current value will be increased and same as when Click on Click to decrease count button then value should decrease after updating state value.

import React, { useState } from "react";
import ReactDOM from "react-dom";

import "./styles.css";

function App() {
  const [count, setCount] = useState(0);

  const increaseCount = () => {
    setCount(prevState => {
      return prevState + 1;
    });
  };

  const decreaseCount = () => {
    setCount(prevState => {
      return prevState - 1;
    });
  };

  return (
    <div className="App">
      <h1>React Hooks</h1>
      <button onClick={increaseCount}>Click to increase count +</button>
      <br /> <br />
      <button onClick={decreaseCount}>Click to decrease count -</button>
      <span id={"counter"} style={styleComp}>
        {count}
      </span>
    </div>
  );
}

const styleComp = {
  fontSize: "100px",
  position: "absolute",
  marginLeft: "-100px",
  marginTop: "30px"
};

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);


Update State Object in React Hook

Sometimes we need to keep update the object (state object) on certain action. Lets say we have user object as state object, having fields like name, age, email etc.

const [user, setUser] = useState({name: 'Manish', 'age': 25, email: '[email protected]'})

So we can update certain fields on particular action.
In above example we have a state object user having one field say name. So we are going to update the state object value whenever we change the value in input box.
for that we are creating a onchange function for updating state object like this.

const onChangeHandle = e => {
    const val = e.target.value;
    setUser(prevState => {
      return { ...prevState, name: val };
    });
  };

Full Code

import React, { useState } from "react";
import ReactDOM from "react-dom";

import "./styles.css";

function App() {
  const [user, setUser] = useState({ name: "" });
  const onChangeHandle = e => {
    const val = e.target.value;
    setUser(prevState => {
      return { ...prevState, name: val };
    });
  };
  return (
    <div className="App">
      <h1>Update React State Object</h1>
      <pre>{JSON.stringify(user, null, 2)}</pre>
      <h3>{user && user.name}</h3>
      <input
        type={"text"}
        placeholder={"Enter Name"}
        onChange={onChangeHandle}
      />
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);


Update State Array Objects in React Hook

Sometimes we have a situation when we need to update state values that stored into array of objects. depending on key value combination we need to update the particular object. So we are assuming a situation where we need to update the day status TRUE OR FALSE.

const val = e.target.checked;
setWeek(prevState => {
let objDay = prevState.find(pre => pre.day === w.day);
objDay.status = val;
return [...prevState];

Full Code

import React, { useState } from "react";
import ReactDOM from "react-dom";
import "./styles.css";
function App() {
  const [week, setWeek] = useState([
    { day: "mon", status: false },
    { day: "tue", status: false },
    { day: "wed", status: false },
    { day: "thu", status: false },
    { day: "fri", status: false },
    { day: "sat", status: false },
    { day: "sun", status: false }
  ]);

  return (
    <div className="App">
      <h1>Update React Array Object State Value</h1>
      {JSON.stringify(week, null, 6)}
      <br />
      <br />
      {week.map((w, index) => {
        return (
          <span key={index}>
            {w.day}
            <input
              type="checkbox"
              checked={w.status}
              onChange={e => {
                const val = e.target.checked;
                setWeek(prevState => {
                  let objDay = prevState.find(pre => pre.day === w.day);
                  objDay.status = val;
                  return [...prevState];
                });
              }}
            />
          </span>
        );
      })}
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Spread the love
Last modified: September 18, 2019

Comments

Write a Reply or Comment

Your email address will not be published.