0

I have one reusable component which receives prop series. That prop contains the data object. Depends on data.length I need to update the component. In case one, data.lenght is 20, and in case two data.length is 6. But when I try to achieve this, component renders only the case where data.length is 20, and when I hit refresh it takes the second case where data.length is 6. I have tried using useEffect() hook but it doesn't work. Apparently I'm missing something. Here is what I've tried so far

const ReusableComponent = ({series}) => { const [propSeries, setSeries] = useState(series.data.length); useEffect(() => { if(propSeries > 6) { // do something } }, [propSeries]) } 

Here is the example of my problem: example. What am I doing wrong?

1
  • useState only gets initialized on the first render. So propSeries will never update unless you do it explicitly with setSeries. Just like in class components: only use state if it is a value that will change over time, and is not a direct copy of props. Otherwise, just use the prop directly Commented May 13, 2020 at 13:19

2 Answers 2

1

Why do you set your props into your state? You could just something like this:

const ReusableComponent = ({series}) => { useEffect(() => { if(series.data.length > 6) { // do something } }, [series]) } 
Sign up to request clarification or add additional context in comments.

Comments

0

The useEffect hook will execute when the component loads set the Series inside the useEffect hook before checking for the length.this way you could implement componentWillReceiveProps functionality using hooks

 const [propSeries, setSeries] = useState(0); useEffect(() => { setSeries(series.data.length); if (propSeries > 6) { alert("Prop Series is Greatar than 6"); } }, [series, propSeries]); 

i created a working example, CodeSadbox here

Hope this helps

1 Comment

@Milos i think your issue may lay somewhere else because the approach is perfectly fine even in your question or in matens answer

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.