0

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?

Nikolai
  • 555
  • 7
  • 17
  • Did you look at https://reactjs.org/docs/hooks-faq.html#how-do-i-implement-getderivedstatefromprops? – jonrsharpe Jul 13 '20 at 11:21
  • @jonrsharpe Yes, the first example (2nd code snippet) I gave was using the documentation. But my question was about using useEffect. Will it work the same and what's the difference? – Nikolai Jul 13 '20 at 11:22
  • 1
    These 2 should do the same thing, but 2. solution is even better since useEffect will only run when specified dependencies change, but getDerivedStateFromProps function runs whenever there is a change in props and you can't really control it. – Danilo Gacevic Jul 13 '20 at 11:26
  • @DaniloGacevic The 1st solution starts tracking the previous state from null so it will go through the if body when the component is rendered for first time. What about the 2nd solution with useEffect? Does it get triggered when the component is rendered for first time? – Nikolai Jul 13 '20 at 11:29
  • 1
    Yes. Every useEffect should run at least once. – Danilo Gacevic Jul 13 '20 at 11:37
  • 1
    `useEffect` runs when the component is first rendered, then every time its deps change after that. – jonrsharpe Jul 13 '20 at 12:33

0 Answers0