2

How do I use prevState with useEffect in a functional component? I was told to update class component to functional component and I'm stuck in the componentDidUpdate part where prevState was used

 componentDidUpdate(prevProps, prevState) {
    if (prevState.search !== this.state.search) {
      this.getData()
    }
    if (prevState.finalSearch !== this.state.finalSearch) {
      if (this.state.finalSearch) {
        this.newData()
      } else {
        this.getRawData()
      }
    }
  }
 

<Search
          search={search}
          finalSearch={finalSearch}
        />
4
  • Could you post more of your code and clarify a bit? It is difficult to tell what your problem is or what you are asking exactly. Typically if you are using useEffect you are not using componentDidUpdate so am a bit confused by your question. Commented Jul 4, 2020 at 19:19
  • I was told to update a class component to functional component and there was this componentDidUpdate in the code and I don't how to change it to useEffect @otw Commented Jul 4, 2020 at 19:20
  • Does this answer your question? Commented Jul 4, 2020 at 19:21
  • Also look at the React docs Commented Jul 4, 2020 at 19:22

4 Answers 4

4

So it looks like you are just using previous state just to avoid unnecessary renders here. This was actually a common enough it was built into useEffect:

componentDidUpdate(prevProps, prevState) {
  if (prevState.count !== this.state.count) {
    document.title = `You clicked ${this.state.count} times`;
  }
}

Becomes:

useEffect(() => {
  document.title = `You clicked ${count} times`;
}, [count]); // Only re-run the effect if count changes

Source: https://reactjs.org/docs/hooks-effect.html#tip-optimizing-performance-by-skipping-effects

Your component might look something like:

useEffect(() => {
  getData()
  
  if (finalSearch) {
    newData()
  } else {
    getRawData()
  }
}, [search, finalSearch]);
Sign up to request clarification or add additional context in comments.

11 Comments

@reactRookie What do you mean by what's wrong? You mean why it is not rendering? I don't really see the code from your question in here.
@reactRookie I am seeing /src/App.js: Unexpected token (159:0)
@reactRookie I updated my answer to have what I think your component should look like. You shouldn't need usePrevious.
@reactRookie functions being underlined is just your compiler telling you there is an error. If you mouse over it, it will tell you why. It seems like there are quite a lot of different issues in that code.
@reactRookie When I type something in it seems to be working just fine when you select a result. If you are saying you see nothing when you just click and select a result, it doesn't look like your blur function is modifying any state.
|
3

You have to create your custom hook usePrevious, refer this: here.

function usePrevious(value) {
  const ref = useRef();
  useEffect(() => {
     ref.current = value;
  });
  return ref.current;
}

Then you have to do this way:

const Component = (props) => {
   const {search, setSearch} = useState('');
   const prevSearch = usePrevious({search, setSearch});
   useEffect(() => {
      if(prevSearch.search !== search) {
          //Your code goes here
      }
   }, [search])
}

2 Comments

So since they are only using the previous values to detect if a render is needed, you don't need a custom hook, this is built into useEffect: reactjs.org/docs/…
@otw yes, for this particular case we can use useEffect hook. But, if we want to use prevState value (for example we have a checkbox and depending on previous value, we need to change it), then the above mentioned way will resolve that issue in particular. Thus depending on situation, we can look for the best approach and apply that for resolving it.
0

You don't have prevState like in class lifecycle components but I think the answer here might help you, just instead for props make it for state

How to compare oldValues and newValues on React Hooks useEffect?

enter image description here

Comments

0

Simply use this

onClick={()=>setShowSearchInput(prevState=>!prevState)}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.