Communicate up component's initial state without useEffect warning

Asked
Active3 hr before
Viewed126 times

10 Answers

communicateuseeffectstatewarninginitialcomponent
90%

eslint warnings are there to warn users about inapproriate use of useEffect. Since hooks depend a lot on closures its extremely important that we write them properly,Now the reason that eslint warns you for missing dependency is because you use onUpdate inside of useEffect, @Leonardo the useEffect warning originates there, 100%. My issue is probably larger: lack of practice with common React patterns. :) – montrealist Apr 23 '20 at 20:31

If you are absolutely sure that what you are writing is correct, you could disable the warning like

useEffect(() => {
   props.onUpdate(from, to);
   // eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
load more v
88%

Start by creating a directory for a Product component:, How To Share State Across React Components with Context ,A React development environment set up with Create React App, with the non-essential boilerplate removed. To set this up, follow Step 1 — Creating an Empty Project of the How To Manage State on React Class Components tutorial. This tutorial will use hooks-tutorial as the project name.

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

Instead of writing asynchronous code without useEffect that might block the UI, utilizing useEffect is a known pattern in the React community — especially the way the React team has designed it to execute side effects.,Hoist functions that don’t need any value of the component scope outside of your component,In this section, I’ll show you some handy patterns that might be useful.

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

React Hooks have quickly become the recommended way to handle component local state and side effects in React function components. Getting started with hooks is quite straightforward, but you might need to change the way you think about your components, especially when it comes to the useEffect hook.,React Hooks were launched in React version 16.8 and they have quickly become a popular way to handle components, local states, and component side effects, among other things. They’re quite easy to get started with, but they're challenging to master properly – you have to learn to think a bit differently compared to React’s traditional class components and lifecycle hooks, and there are certain rules that you have to follow. ,If you want to learn more about hooks and the rules of hooks, React’s official docs are amazing – they explain the rules and why you have to follow them. If I had read them to start with I wouldn’t have made the mistakes I did! I’d also recommend taking a look at Dan Abramov’s blog, overreacted.io. A complete guide to useEffect is interesting, as is React as a UI Runtime, and how are function components different from classes will teach you some important differences.

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

Just as we were able to set up useEffect to run when a state variable changed, the same can be done with props. Remember they’re all regular variables! useEffect can trigger on any of them.,Pretty much anything you want to “do” in a React component other than return JSX (any sort of side effect), will go into a useEffect. (and you can have more than one useEffect per component, too),If you’ve used class components and lifecycle methods, read this section first.

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

componentDidMount fires and sets state immediately (not in an async callback),With the class-based code, componentDidMount doesn't have closure over state so it just reads whatever the current value is.,Component renders for the first time.

class App extends React.Component {
  state = {
    count: 0
  };

  componentDidMount() {
    longResolve().then(() => {
      alert(this.state.count);
    });
  }

  render() {
    return (
      <div>
        <button
          onClick={() => {
            this.setState(state => ({ count: state.count + 1 }));
          }}
        >
          Count: {this.state.count}
        </button>
      </div>
    );
  }
}
load more v
22%

This example renders a counter with a value of 0. When you click the button, it increments the value by 1. The initial value of the component is defined using useState.,Now, this component will be maybe to successfully manage its state if it remains the same between multiple calls of useState and useEffect.,There are some benefits you get by using functional components in React:

function Form() {
   // 1. Use the accountName state variable
   const [accountName, setAccountName] = useState('David');

   // 2. Use an effect for persisting the form
   useEffect(function persistForm() {
      localStorage.setItem('formData', accountName);
   });

   // 3. Use the accountDetail state variable
   const [accountDetail, setAccountDetail] = useState('Active');

   // 4. Use an effect for updating the title
   useEffect(function updateStatus() {
      document.title = accountName + ' ' + accountDetail;
   });

   // ...
}
load more v
60%

If you have ever worked with useEffect, you have probably come across the following lint warning:,You might try to solve the lint warning by adding params to the dependency array of the useEffect:,In effect, we have a “gate.” We should only run the code inside the useEffect when certain conditions have been met.

If you have ever worked with useEffect, you have probably come across the following lint warning:

React Hook useEffect has a missing dependency.Either include it or remove the dependency array.
load more v
48%

This is starting to crop up more and more in third party libraries now: urql, Apollo.,This issue was the closest I could find regarding this problem.,If you guys have any suggestion to solve this warning i would appreciate it``

console.error node_modules / react - dom / cjs / react - dom.development.js: 88
Warning: Cannot update a component from inside the
function body of a different component.
in Route(at App.tsx: 37) in View(created by StackManagerInner) in ViewTransitionManager(created by StackManagerInner) in ion - router - outlet(created by IonRouterOutlet) in IonRouterOutlet(created by ForwardRef(IonRouterOutlet)) in ForwardRef(IonRouterOutlet)(created by StackManagerInner) in StackManagerInner(created by Context.Consumer) in Unknown(created by Component) in Component(created by ForwardRef(IonRouterOutlet)) in ForwardRef(IonRouterOutlet)(at App.tsx: 36) in ion - split - pane(created by IonSplitPane) in IonSplitPane(created by ForwardRef(IonSplitPane)) in ForwardRef(IonSplitPane)(at App.tsx: 34) in NavManager(created by RouteManager) in RouteManager(created by Context.Consumer) in RouteManager(created by IonReactRouter) in Router(created by BrowserRouter) in BrowserRouter(created by IonReactRouter) in IonReactRouter(at App.tsx: 33) in ion - app(created by IonApp) in IonApp(created by ForwardRef(IonApp)) in ForwardRef(IonApp)(at App.tsx: 32) in App(at App.test.tsx: 6)
load more v
23%

Warning: Can’t perform a React state update on an unmounted component. This is a no-op, but it…,If you are a react developer, there is a good chance that you faced this warning at least once:

Pretag
 Pretag team - issue, fix, solve, resolve

Other "communicate-useeffect" queries related to "Communicate up component's initial state without useEffect warning"