Paul
Paul

Reputation: 4438

React Hooks update a state element when an update of a specific props element occurs

Normally not using hooks I used componentWillReceiveProps, but using hooks I can't use them.

How can I update an element of the state when a prop is updated, without going into infinite cycles.

I was trying something like this but I'm going on in endless cycles.

I need to update the datatable when it changes state, or the page etc, then update only specific item if it changes state and is different from the original that was passed.

I thought about doing this, but I don't really like it as a solution.

    if(datatable !== state.datatable)
    setState({ ...state, datatable });

Can you give me some advice?

function Datatable({ header, datatable = [], page = 1, perPage = 5, style }) {
    const [state, setState] = useState({
        datatable,
        page: page - 1,
        perPage,
        numberOfPages: Math.ceil(datatable.length / perPage),
    });

useEffect(() => {
        setState({ ...state, datatable });
 });
 ....
}

Upvotes: 0

Views: 106

Answers (2)

Vahid Boreiri
Vahid Boreiri

Reputation: 3438

It's a bad pattern to put the prop value in a state. In this way, you have two sources of truth for datatable value. Additionally, your component will re-render by changing props itself and you don't need to put it in the state.

The following code will do what you want:

function Datatable({ header, datatable = [], page = 1, perPage = 5, style }) {
    const [state, setState] = useState({
        page: page - 1,
        perPage,
        numberOfPages: Math.ceil(datatable.length / perPage),
    });
 ....
}

Upvotes: 1

ravibagul91
ravibagul91

Reputation: 20755

You need to pass datatable as dependency to useEffect hook,

useEffect(() => {
        setState({ ...state, datatable });
},[datatable]);

Now your hook will execute when datatable changes only.

Upvotes: 1

Related Questions