Use Component State Initializers

InstructorKent C. Dodds

Share this video with your friends

Send Tweet

In this lesson, we'll allow users to initialize our component's state with their own defaults and support a reset functionality to reset to the initial state.

Wix
~ 6 years ago

Hi, Can you elaborate about the case where Toggle is re-rendered with a different value for initialOn?

Erez erezm@wix.com

Kent C. Doddsinstructor
~ 6 years ago

If it's re-rendered with a different value for initialOn then I would consider that to be a mistake on the user's part. If they want to actually change the value that the component gets reset to they can either use a key prop to force react to unmount and remount a new instance, or they can use control props.

Thein
~ 6 years ago

if multiple buttons with combine behaviors, how will you manage it? For example onoff button plus reset state button?

Thein
~ 6 years ago

I got it; I can use switch statement at getTogglerProps and use id;

Ann
~ 6 years ago

Hi, I am confused why you are not using the constructor(props) method to set the initial state. Is this a style preference or is there a benefit to setting it the way you have in this example?

Kent C. Doddsinstructor
~ 6 years ago

We're using public class fields. Learn more about them here: https://egghead.io/lessons/react-use-class-components-with-react and here: https://egghead.io/lessons/javascript-public-class-fields-with-react-components

Thein
~ 6 years ago

Ann, if you use babel transpiler, at your project root .babelrc file, you can set plugins :["transform-class-properties"]