25

Everytime I get new data in data prop but the component dont re-render untill I call handlePanelSelection()

function StepPanel({ data, getTranslations }) {
  const [panelsData, changePanel] = useState(data);

  function handlePanelSelection(panelId) {
    switch (panelId) {
      case 8:
        changePanel(getTranslations.NeeSubCategory);
        break;
      default:
        changePanel(data);
        break;
    }
  }
  return (
    <>
      {panelsData.map(details => {
        const imgsrc = requireContext('./' + details.image);
        return (
          <div key={details.id} className="block-list">
            <div className="left-block">
              <img src={imgsrc} alt="" />
            </div>
            <div className="right-block">
              <h3>{details.title}</h3>
              <p>{details.description}</p>
              <label htmlFor="radio1" className="radio-btn">
                <input
                  type="radio"
                  onClick={() => handlePanelSelection(details.id)}
                  name="radio1"
                />
                <span></span>
              </label>
            </div>
          </div>
        );
      })}
    </>
  );
}

but when I remove the hook like below it works

function StepPanel({ data, getTranslations }) {
 
  return (
    <>
      {data.map(details => { ... })}
    </>
  )
}

I want to implement a functionality that when I get new data in data props the component gets re-render but also when I need to internally re-render i.e. like I change panelId = 8, then also it gets re-render, is it possible with this approach?

The above code seems to rerender but with the same data every time i.e. Its not updating the panelData everytime although everytime the data props is being provided with a new updated value

console image

2
  • please show the error in your console. it will have useful information. Nov 16, 2019 at 7:10
  • Hello @LongNguyen I have consoled for the error, it seems to rerender but the data in panelsData does not change every-time its showing the same results although the data props is giving me the updated value every-time I will update my question for correct query
    – Adarsh
    Nov 16, 2019 at 7:21

4 Answers 4

71

This is because when you do this:

const [panelsData, changePanel] = useState(data);

You're only using your data prop as the initial value of panelsData. When the props change, the new data will be ignored because panelsData has its own state (well, it's a useState hook!).

That's why you have to explicitly call changePanel to change the state. That's the whole idea!

If you want to observe the data prop and update the state accordingly, you could use a useEffect hook with data as dependency (that means, it'll run only when data changes), like this:

useEffect(() => {
  changePanel(data);
}, [data]);
6
  • 1
    Thank you so much @ezakto that works exactly I want, and answer my problem.
    – Adarsh
    Nov 16, 2019 at 7:42
  • perfect solution to what was ailing me as well. Good explanation too. I didn't know you could pass props to useEffect like that, I thought it was state only.
    – ICW
    Dec 19, 2019 at 0:05
  • @YungGun You can set anything in the array of dependencies. When the component re-renders, it'll check all the elements of the array to see if at least one has changed, no matter where the value comes from.
    – ezakto
    Dec 20, 2019 at 18:13
  • Brilliant solution! I kept thinking, "If only there was a native way to set state only when the prop changed." It's been a long day...
    – musicin3d
    Mar 6, 2020 at 22:44
  • 1
    Thank you, I too didn't realize props could be used as useEffect deps
    – redditmerc
    Mar 27, 2022 at 3:01
0

Have you ever try useEffect to handle re-render of component:

function handlePanelSelection(panelId) {
    switch (panelId) {
      case 8:
        changePanel(getTranslations.NeeSubCategory);
        break;
      default:
        changePanel(data);
        break;
    }
}
useEffect(() => {

}, [panelsData]) // just pass panelsData into here
// Component will re-render when panelsData change.
1
  • Hello @jdn I tried to use the above code and consoled for the error it seems to rerender but the data in panelsData does not change every-time its showing the same results although the data props is giving me the updated value every-time
    – Adarsh
    Nov 16, 2019 at 7:19
0

Does it work if you replace this part of your code?

  // this block creates new function when re-render
  // replace
  function handlePanelSelection(panelId) {
    switch (panelId) {
      case 8:
        changePanel(getTranslations.NeeSubCategory);
        break;
      default:
        changePanel(data);
        break;
    }
  }
  // by
  const handlePanelSelection = useCallback(()=> {
    switch (panelId) {
      case 8:
        changePanel(getTranslations.NeeSubCategory);
        break;
      default:
        changePanel(data);
        break;
    }
  }, [data, getTranslations])
-1

Instead of using useEffect() as mentioned by @ezakto we can do like this:

const copyData = JSON.parse(JSON.stringify(data));

if(panelsData !== copyData){
    changePanel(data);
}

So that their will be no re-renders and your application will be somewhat efficient.

1
  • Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
    – Community Bot
    Sep 30, 2022 at 9:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.