reactjsreact-hooks

Component doesn't re-render when props change using useState hook


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


Solution

  • 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]);