Can you replicate static setDerivedStateFromProps with useEffect in Functional Component (React)?

115 Views Asked by At

I'm reading a book for React (beginner book) and I'm not quite sure how to replicate this lifecycle static function setDerivedStateFromProps

This is the code with a class approach (but I need this with functional approach):

public static getDerivedStateFromProps(
 props: RouteComponentProps,
 state: IState
) {
 const search = (new URLSearchParams(props.location.search)).get("search") || "";
 return {
 state.products,
 search
 } as IState;
}

I saw the React documentation and they've given an example. I'm not entirely sure what it means and if it will work for me, but I tried to use it as a reference and I wrote this:

const [state, setState] = useState(defaultState);
const [previousState, setPreviousState] = useState(null);

if (state !== previousState) {
  const search = (new URLSearchParams(props.location.search)).get("search") || "";
  setState({state.products, search} as IState);
  setPreviousState(state);
}

Will the above code work as setDerivedStateFromProps? What's the difference between the code above and using useEffect like this:

const [state, setState] = useState(defaultState);
useEffect(() => {
  const search = (new URLSearchParams(props.location.search)).get("search") || "";
  setState({state.products, search} as IState);
}, [ props.location.search ]);

Will this work exactly as setDerivedStateFromProps?

0

There are 0 best solutions below