Search code examples
reactjsreact-hookssetstate

how can I know whether render reason is property changed or state changed in react hook function?


I have a displayer component implemented by react hook. The displayer component receives a set of records by property named 'rows'. It has two buttons used to show previous or next one, so I use a state named 'index' represents the current row no.

It is easy to show prev/next one by decrease or increase the state 'index'. But when its rows changed, I want reset index to zero. How can I get the right condition without saving a copy of the rows to compare them?

interface row {
  id: number;
  name: string;
}
interface tableProps {
  rows: row[];
}
const Shower: React.FC<tableProps> = (props) => {
  const [index, setIndex] = useState<number>(0);
  // when should I reset the index to zero when receiving a new property rows?
  return <div>  
    <button disabled={!(index > 0)} onClick={() => setIndex(index - 1)}>Prev</button>
    <span>{props.rows[index].id}:{props.rows[index].name}</span>
    <button disabled={!(index + 1 < props.rows.length)} onClick={() => setIndex(index + 1)}>Prev</button>
  </div>;
}

Solution

  • You can use useEffect

    ......
    
    import {useEffect} from 'react'
    ....
    
    useEffect(()=>{
       setIndex(0)
    },[props.rows])