Passing State from useEffect to Function in Component?

Asked
Active3 hr before
Viewed126 times

8 Answers

functionuseeffectcomponentstate
90%

Your problem is, that you are mutating state by accident. Seems like React chooses not to rerender your component in this case, so reorderActiveCardsDown still has the old data.,Connect and share knowledge within a single location that is structured and easy to search.,To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

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

The Effect Hook lets you perform side effects in function components:,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:,This snippet is based on the counter example from the previous page, but we added a new feature to it: we set the document title to a custom message including the number of clicks.

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%

In the above example the fetchUsers call will only happen once, since it isn't listing any variables in the dependency array. It's also displaying the user's first name, last name, and email in the component.,In this example, the useState and useEffect code just moved into the custom hook. This code will function just like it did when it was inside of the App component.,Hooks only work in functional components. They will not work inside of a class component.

1import React from 'react';
2
3export default function App() {
4  const [users, usersSet] = React.useState([]);
5  return (
6    <div>
7      <ul>{users}</ul>
8    </div>
9  );
10}
load more v
65%

Run useEffect When a Prop Changes,Run useEffect on State Change,When Does useEffect Run?

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

function LifecycleDemo() {
  // Pass useEffect a function
  useEffect(() => {
    // This gets called after every render, by default
    // (the first one, and every one after that)
    console.log('render!');

    // If you want to implement componentWillUnmount,
    // return a function from here, and React will call
    // it prior to unmounting.
    return () => console.log('unmounting...');
  })

  return "I'm a lifecycle demo";
}

function App() {
  // Set up a piece of state, so that we have
  // a way to trigger a re-render.
  const [random, setRandom] = useState(Math.random());

  // Set up another piece of state to keep track of
  // whether the LifecycleDemo is shown or hidden
  const [mounted, setMounted] = useState(true);

  // This function will change the random number,
  // and trigger a re-render (in the console,
  // you'll see a "render!" from LifecycleDemo)
  const reRender = () => setRandom(Math.random());

  // This function will unmount and re-mount the
  // LifecycleDemo, so you can see its cleanup function
  // being called.
  const toggle = () => setMounted(!mounted);

  return (
    <>
      <button onClick={reRender}>Re-render</button>
      <button onClick={toggle}>Show/Hide LifecycleDemo</button>
      {mounted && <LifecycleDemo/>}
    </>
  );
}

ReactDOM.render(<App/>, document.querySelector('#root'));
load more v
75%

A functional React component uses props and/or state to calculate the output. If the functional component makes calculations that don’t target the output value, then these calculations are named side-effects.,C) Finally, after unmounting the component, useEffect() invokes the cleanup function from the latest side-effect.,useEffect() can perform data fetching side-effect.

function Greet({ name }) {
  const message = `Hello, ${name}!`; // Calculates output

  // Bad!
  document.title = 'Greetings page'; // Side-effect!
  return <div>{message}</div>;       // Calculates output
}
load more v
40%

We have seen how to pass state data between function components. ,Now lets go ahead and create our Salary Component. This Salary Component function receives two inputs. One is the Salary value and the other one is the callback function. ,In this article, we will discuss about passing data from Parent Compnonent to child Component and from Child Component back to Parent Component when the Components are function Components.

Save the changes. Navigate to the browser. We can see that If we enter Salary in Employee Component, it gets updated in Salary Component and if we change it Salary Component, it gets updated into Employee Component. 

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

function NewEmployee(){

  const [employee,setEmployeeData]=useState({Id:'',Name:'',Location:'',Salary:''});    

  function changeEmployeeInfo(e){

    console.log(e);

    setEmployeeData({...employee,[e.target.name]:e.target.value});

  }

  return(

    <div>

      <h2>Welcome to Employee Component...</h2>

      <p>

        <label>Employee ID :

                <input type="text" name="Id" value={employee.Id}

                onChange={changeEmployeeInfo}></input>

        </label>

      </p>

      <p>

        <label>Employee Name : 

                <input type="text" name="Name" value={employee.Name} 

                onChange={changeEmployeeInfo}></input>

        </label>

      </p>

      <p>

        <label>Employee Location :

                <input type="text" name="Location" value={employee.Location}

                onChange={changeEmployeeInfo}></input>

        </label>

      </p>

      <p>

        <label>Employee Salary : 

                <input type="text" name="Salary" value={employee.Salary}

                onChange={changeEmployeeInfo}></input>

        </label>

      </p>

      <p>

        Employee ID is : <b>{employee.Id}</b>, Name is : <b>{employee.Name}</b> ,

         Location is : <b>{employee.Location}</b> and Salary is : <b>{employee.Salary}</b>

      </p>

      <SalaryComponent onSalaryChange={changeEmployeeInfo} salary={employee.Salary}></SalaryComponent>

    </div>

  )

}

const SalaryComponent=({onSalaryChange,salary})=>{

  function changeSalary(e){

    onSalaryChange(e);

  }

  return(

    <div style={{border:'3px solid red', width:'500px'}}>

      <h2>Welcome to Salary Component</h2>

    <p>

        <label>Employee Salary : 

                <input type="text" name="Salary" value={salary}

                onChange={changeSalary}></input>

        </label>

      </p>

    </div>
  );

}

const element=<NewEmployee></NewEmployee>

ReactDOM.render(element,document.getElementById("root"));
22%

Technofunnel brings another article on “useEffect Hook in React”. Hooks are the new features of React 16.8. We can create state variables and other features of React without using Class-Based Components. Hooks are used for Function Components. We have various Hooks provided by React:

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

A setter function (e.g. — setState) that is executed during a particular point in the component’s lifecycle to update the value(s) of the state’s data structure/type.,Hooks let us split the code based on what it is doing rather than a lifecycle method name.,Rather, think of useEffect() as a function that executes specific tasks for your component before rendering (often referred to as “cleaning”), after rendering, and before the component’s unmount.

Pretag
 Pretag team - issue, fix, solve, resolve

Other "function-useeffect" queries related to "Passing State from useEffect to Function in Component?"