Reputation: 189
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}
/>
Upvotes: 2
Views: 8070
Reputation: 1145
Simply use this
onClick={()=>setShowSearchInput(prevState=>!prevState)}
Upvotes: 0
Reputation: 660
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]);
Upvotes: 4
Reputation: 381
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])
}
Upvotes: 3
Reputation: 803
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?
Upvotes: 0