A practical exercise about Thinking in React - Step 4: Identify Where Your State Should Live.
Using an empty create-react-app project (link bellow), we will add a few features to illustrate modelling of components with static content, when to turn them into reusable components and how to choose a good time to add dynamic behaviour (i.e. with user input and API requests - illustrated on a Search feature). After a short brake for an open discussion with refreshments, we will implement a more complex feature (e.g. a Router with Back/Forward navigation and a Cache). The main objective will be to clarify the decision making process about application state.
cd react-workshop/00-props-state # or whereever you want to create a repo
create-react-app live_coding
Excercises (follow live coding / create your own example / help people around when finished):
- 00-init
- hardcoded content without any props or state, all at top level
- 01-props
- create components, identify what should be props
- 02-state
- create wrapper components for state
- 03-shared-state
- lift the state up in the hierarchy as needed
Git diffs (to discuss concepts that would take longer to code):
- 04-router
- use a simplified version of react-router to preserve some state via URL
- 05-context
- use the React Context to avoid passing props in intermediate components
- 06-hooks
- a teaser of React Hooks (more in a separate workshop)
- 07-redux
- convert to Redux to simplify debugging with dev tools or if we cannot use alpha features in our project
<input value=...
is called a Controlled Component (by React),
<input defaultValue=...
is Uncontrolled (controlled by DOM / browser)class ... method = () => ...
is Class Fields feature<A>{(x) => <B prop={x} />}</A>
is Render Props (a.k.a "children as a function")<>
is syntax sugar for<React.Fragment>
- for reusable components, see also distinction between smart/dumb (a.k.a logical/presentational) components, e.g. https://youtu.be/Y7es1vcib14
Enhanced = withSomething(Wrapped)
is a Higher Order ComponentcomponentWillReceiveProps
=> see You Probably Don't Need Derived State
TODO: update tips during live coding if needed