React component not re-rendering after using UseState Hook [duplicate]

Asked
Active3 hr before
Viewed126 times

8 Answers

usingcomponentreact
90%

I found the answer here: UI not re-rendering on state update using React Hooks and form submission,The function is working properly, changing the schools' state; I can see that from the console, but the elements are not re-rendering., Movie Where Male Playwright Brings Characters into Existence by Speaking into a Recorder

You need to pass a new instance to setScholls for the component to re-render, try this :

const sortSchools = (key, value) => {
   setSchools([...schools.sort(compareValues(key, value))]);
   console.log(schools);
}
88%

When an update is made to a ref, the shallow rendering mechanism is used to re-render the component.,The component is then re-rendered.,We can force React to re-render a component, even when there is no need for the update by using a non-reference useState update function.

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
72%

This Class component code is similar to our functional hook component. But in this class component changes are rerender but not in functional hook component. Does react uses the Object.is comparison algorithm only in case of Hooks?,The state updater returned by useState will not rerender the component's children if you set a new value that equals the current value. https://reactjs.org/docs/hooks-reference.html#bailing-out-of-a-state-update, Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

import React, { useState } from "react";

function Example() {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = useState({
    name: "pankaj",
    age: 12,
    city: "alwar"
  });
  const [data, updateData] = useState([
    { id: 1, name: "Pankaj 1" },
    { id: 2, name: "Pankaj 2" },
    { id: 3, name: "Pankaj 3" },
    { id: 4, name: "Pankaj 4" }
  ]);

  const updateStateData = id => {
    let item = data.find(item => item.id == id);
    item.name += " updated 1";
    updateData(data);
  };

  return (
    <div>
      <p>You clicked {count.name} name</p>
      <p>You clicked {count.age} age</p>
      <p>You clicked {count.city} city</p>
      <button
        onClick={() =>
          setCount({
            name: count.name + " updated",
            age: count.age,
            city: count.city
          })
        }
      >
        Update Name
      </button>
      <button
        onClick={() =>
          setCount({ name: count.name, age: count.age + 10, city: count.city })
        }
      >
        Update Age
      </button>
      <button
        onClick={() =>
          setCount({
            name: count.name,
            age: count.age,
            city: count.city + " updated"
          })
        }
      >
        Update City
      </button>

      <div>
        {data.map(item => {
          console.log({ item });
          return (
            <div>
              <p>{item.id}</p>
              <p>{item.name}</p>
              <button onClick={() => updateStateData(item.id)}>Update</button>
            </div>
          );
        })}
      </div>
    </div>
  );
}

export default Example;
load more v
65%

Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class.,If you’re used to classes, you might be wondering why the effect cleanup phase happens after every re-render, and not just once during unmounting. Let’s look at a practical example to see why this design helps us create components with fewer bugs.,Other effects might not have a cleanup phase, and don’t return anything.

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
75%

Figure 1. When you change a value in a component, React should update the UI.,React knows the state value has changed so must recalculate the UI.,#D Use the updater function to change the state value

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

So when should you use the useState Hook? It’s especially useful for local component state, but larger projects might require additional state management solutions.,You can pass it directly, as shown in the previous example, or use a function to lazily initialize the variable (useful when the initial state is the result of an expensive computation):,For advanced use cases, you can use the useReducer Hook as an alternative to useState. This is especially useful when you have complex state logic that uses multiple sub-values or when a state depends on the previous one.

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

To avoid re-rendering per component with the you will use the shouldComponentUpdate() lifecycle.if(typeof __ez_fad_position != 'undefined'){__ez_fad_position('div-gpt-ad-linguinecode_com-medrectangle-4-0')};,The first step is to add the shouldComponentUpdate lifeycle to the greeting component and make it return false.,In the code image above, I’m console logging a message when the component gets to the shouldComponentUpdate lifecycle.

componentDidMount() {
  this.setState({ ruinPerformance: true });
}

render() {
  return (
    <SubComp>
      <SubComp>
        <SubComp>
          <SubComp>
            Hello world :)
          </SubComp>
        </SubComp>
      </SubComp>
      <SiblingComp />
    </SubComp>
  );
}
load more v
60%

Call useState() hook to enable state in a functional component.,useState() is correctly called at the top level of functional component:,A functional component can have as many states as necessary by doing multiple calls of useState().

import React from 'react';

function Bulbs() {
  return <div className="bulb-off" />;
}
load more v

Other "using-component" queries related to "React component not re-rendering after using UseState Hook [duplicate]"