React useEffect don't change state [duplicate]

Asked
Active3 hr before
Viewed126 times

7 Answers

statereact
90%

Maybe API function that you is used is async ? If yes, useEffect parameter callback is not async and can't be async maybe :D. Reference React Hooks. Solution : You can use sperate function API async and call on useEffect function. Maybe you can refer on this link Example For useEffect async,Possibility that problem can be caused by :, There is no problem, the state is updated, its not just seen in the same render cycle. If you log the state in useEffect with a dependency on games, you will see the update – Shubham Khatri Jun 11 '20 at 10:13

Pretag
 Pretag team - issue, fix, solve, resolve
88%

The Effect Hook lets you perform side effects in function components:,Data fetching, setting up a subscription, and manually changing the DOM in React components are all examples of side effects. Whether or not you’re used to calling these operations “side effects” (or just “effects”), you’ve likely performed them in your components before.,We’ve learned that useEffect lets us express different kinds of side effects after a component renders. Some effects might require cleanup so they return a function:

import React, { useState, useEffect } from 'react';
function Example() {
  const [count, setCount] = useState(0);

  // Similar to componentDidMount and componentDidUpdate:  useEffect(() => {    // Update the document title using the browser API    document.title = `You clicked ${count} times`;  });
  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}
load more v
72%

Is there a recommended way to update state or globals, using hooks, before the render happens?,In short, if you are using the second parameter [] then you need to put all the variable (state or not) that you rely on.,What is the current behavior? scroll state variable updates in rendered output but not inside handleScroll event callback.

import React, { useState, useEffect } from "react";

const Scroller = () => {
  const [scroll, setScroll] = useState(window.scrollY);

  const handleScroll = () => {
    console.log(scroll); // scroll is always 0
    setScroll(window.scrollY);
  };

  useEffect(() => {
    window.addEventListener("scroll", handleScroll);
    return () => window.removeEventListener("scroll", handleScroll);
  }, []); // runs once

  return <div id="scroll">{scroll}</div>; // scroll is correct
};

export default Scroller;
load more v
65%

Updating a state variable is as simple as invoking the updater function returned by the useState invocation: const [stateValue, updaterFn] = useState(initialStateValue);.,The updater function returned from invoking useState can also take a function similar to the good ol’ setState:,Declaring a state variable is as simple as calling useState with some initial state value, like so: useState(initialStateValue).

Pretag
 Pretag team - issue, fix, solve, resolve
75%

When a new update is available for the component through an update to its props or state, React pulls the old value for states and refs from its store and re-initializes the state to the old value also applying an update to the states and refs that have an update.,A workaround for the repeated re-rendering is using a local variable within the component to hold the toggled state which can also be updated to prevent the frequent re-rendering — which is carried out only when there is an update to local states or props of a component.,Deep re-rendering is used when an update is carried out on a state using the useState hook or an update to the component’s props.

function Card (props) {
  let toggled = false;
  
  const handleToggleBody = () => {
    toggled = true;
    console.log(toggled);
  };

  useEffect(() => {
    console.log(“Component rendered, the value of toggled is:“, toggled);
  }, [props.title]);

  return (
    <section className=“card”>
      <h3 className=“card__title” onMouseMove={handleToggleBody}>
        {props.title}
      </h3>

      {toggled && <article className=“card__body”>{props.body}</article>}
    </section>
  );
}

// Renders the application
function App () {
  
  const [cardDetails, setCardDetails] = useState({
    title: “Something”,
    body: “uniquely done”,
  });

  useEffect(() => {
    setTimeout(() => {
      setCardDetails({
        title: “We”,
        body: “have updated something nice”,
      });
    }, 5000); // Force an update after 5s
  }, []);

  return (
    <div>
      <Card title={cardDetails.title} body={cardDetails.body} />
    </div>
  );
}
load more v
40%

As you would expect we also have an update function for each name so that you can handle changes to them independently.,A Complete Guide to useEffect,Finally, we have one more update we need to make before the ADD_TODO will work. Inside of our JSX we are still mapping over initialState. We need to change that from the line below:

Pretag
 Pretag team - issue, fix, solve, resolve
22%

In other words, the hook compares (===) the “old” and “new” state and concludes that the object hasn’t changed, and won’t trigger a re-render, causing the object count label to stay the same😭.,It basically keeps the same object properties but creates a new object reference so that the hook strict equality comparison determines that the state changes, and immediately triggers a re-render.,The problem with this is that the useState hook uses strict equality comparison to determine if it should trigger a re-render and doesn’t check if the properties of the object actually changed.

const { useState } = React;

const Counter = () => {
  const [count, setCount] = useState(0);
  const [objectCount, setObjectCount] = useState({ count: 0 });

  return (
    <div>
      <h2>Count</h2>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>Increase normal count</button>

      <h2>Object Count</h2>
      <p>You clicked {objectCount.count} times</p>
      <button
        onClick={() => {
          objectCount.count += 1;
          setObjectCount(objectCount);
        }}
      >
        Broken increase of the object count
      </button>

      <br />
      <br />

      <button
        onClick={() =>
          setObjectCount({
            ...objectCount,
            count: objectCount.count + 1,
          })
        }
      >
        Functioning increase of the object count
      </button>
    </div>
  );
};

ReactDOM.render(<Counter />, document.getElementById('app'));

Other "state-react" queries related to "React useEffect don't change state [duplicate]"