Reputation: 614
I'm currently trying to convert some hooks over to being inside class components in React. I'm attempting to recreate the code that allows for session storage so that the app doesn't need to fetch from the API so much. Here is the code:
useEffect(() => {
if(sessionStorage.homeState){
// console.log("Getting from session storage");
setState(JSON.parse(sessionStorage.homeState));
setLoading(false);
}else{
// console.log("Getting from API");
fetchMovies(POPULAR_BASE_URL);
}
}, [])
useEffect(() => {
if(!searchTerm){
// console.log("Writing to session storage");
sessionStorage.setItem('homeState', JSON.stringify(state));
}
}, [searchTerm, state])
These are two useEffect hooks so it makes sense to me to go with a regular componentDidMount to get from the session storage. The only thing that I can't seem to figure out is how to recreate the second useEffect that sets session storage and fires only when searchTerm or state changes. searchTerm and state are simply two properties of the state. How could I implement this since componentDidMount only fires once when the app first mounts? Thanks
Upvotes: 0
Views: 53
Reputation: 1271
The only thing that I can't seem to figure out is how to recreate the second useEffect that sets session storage and fires only when searchTerm or state changes. searchTerm and state are simply two properties of the state.
componentDidMount()
is only one of methods used by the class components you can recreate the second hook with componentWillUpdate() or shouldComponentUpdate().
For example:
componentWillUpdate(nextProps, nextState) {
if (this.props.searchTerm !== prevProps.searchTerm) {
...
}
}
You can check what lifecycle methods are available in class components by Googling "class component lifecycle".
But as you can read in the comment to your questions Hooks can offer you more than class components, and recreating them is not trivial. It is easier to move from the class component to the Hooks.
Upvotes: 1