Languages
[Edit]
EN

React - change state from props (functional component)

3 points
Created by:
Iona
445

In this article, we would like to show you how to change component state from props in React when we work with functional components.

This article shows two approaches:

  • with useEffect what is the most popular approach in many projects that causes additional re-rendering component cycle,
  • with a custom hook that bases on useRef - which is the optimal solution.

1. useEffect approach example

Edit

Below example uses two functional components: MyComponent and App.

States are stored in globalCounter and localCounter. Every button click action inside App component causes passing globalCounter into MyComponent localCounter state via counter props. useState creates state with indicated value only once, so in the below case useState(counter) with new couter value will not cause state change. By using useEffect hook we are able to monitor counter prop value with indicating dependencies via [counter] and update localCounter value with setLocalCounter function always when useEffect detects couter value changes.

2. Optimal solution

Edit

Below examples uses useRef and useState to store property and state.

2.1. with useState

Edit

2.2. with useRef example

Edit

Below approach is a little complicated because uses references to store state. The main idea of the solution is to store state inside reference and force rerendering with counter when the state is changed.

Alternative titles

  1. React - change state on props change (functional component)
1
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

ReactJS

React - change state from props (functional component)
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join