Home > Software design >  How do I call useEffect when the trigger is in another component?
How do I call useEffect when the trigger is in another component?

Time:08-05

I am trying to fetch data in a functional React component using useEffect (since the function is asynchronous) and I compute and return the data in h2 tags that was fetched in this component. However, I want to fetch the data when in another component (App.js) I hit the enter key. I have an enter key handler which calls a useState which I believe should re-render the component but since the useEffect is in another component, I am not getting the calling of the useEffect as I intend. What is the best method to press the Enter key and have useEffect in another component run?

function handleKeyDown(event){

if(event.key === 'Enter'){
  //this setHeadingText is a useState variable which should re-render in App.js
  setHeadingText(name);
}

CodePudding user response:

It sounds like your useEffect is specifying an empty dependency array (instructing to run only once):

useEffect(() => {
  //fetch some data
}, []); // This empty array ensures it only runs 1 time

Have a look at this section in the docs: https://reactjs.org/docs/hooks-effect.html#tip-optimizing-performance-by-skipping-effects

If your second component has access to your headingText state, try specifying your headingText as a dependency to the useEffect, and any changes to it should trigger your useEffect

useEffect(() => {
  //fetch some data
}, [headingText]); // Only re-run the effect if headingText changes

Alternatively, remove the dependency array from your useEffect.

Note: this will cause the useEffect to run on every re-render

useEffect(() => {
  //fetch some data
}); // run every time the component re-renders

CodePudding user response:

Now that I have understood properly, I think this is the solution you wished for:

  1. The headingText value that is being updated in your App.jsx component should be passed down to your Child component with the help of props. So use <Child headingText={headingText} /> while loading the Child component in your App.jsx.
  2. Inside your Child component, receive the value like this function Child(props) or function Child({ headingText }) if you have more values to pass, prefer props.
  3. Now you can easily access the changes in value made in your App component inside your Child component with the help of props.headingText or headingText respective to the way you defined your Child in point 2.
  4. To re-render your Child component, you will now use the useEffect hook with its dependency set to headingText, like:
React.useEffect(() => 
    {
    // Code for refetching
    }
, [headingText]); // or props.headingText if your Child component uses (props)

For example: CodeSandbox
Hope that helps you!

  • Related